Home > database >  How to avoid selecting the same elements in a list?
How to avoid selecting the same elements in a list?

Time:10-09

Assume there two lists:A=[1,2,3,4,5,6,7];B=[23,25,34,23,24,10,45]. The elements in A List represent the name of products, while those in B list represent the price of products. For example, product 1 worths 23 USD. I want to retrieve the products whose price is 23 USD. What I tried was shown below:

Prod_23 = []
for i in B:
  if i == 23:
    index = B.index(i)
    product = A[index]
    Prod_23.append(product)

The result was:

Prod_23 = [1,1]

But the actual result should be like:

Prod_23 = [1,4]

Could you please give me some clues of avoiding selecting the first element twice and only selecting the first and fourth elements?

CodePudding user response:

Use zip() to tie lists A and B together and use list-comprehension:

list_23 = [a for a, b in zip(A, B) if b == 23]
print(list_23)

Prints:

[1, 4]

CodePudding user response:

why don't do this:

a[b.index(23)]
  • Related