简体   繁体   中英

compare between item of list with index of another list in python

I would like to compare between two list using item of the first list with index of the second list, and new list will append from second list for each matched.

a = [[1],[0],[0]]
b = [[1,2],[3,4],[5,6]]
c = []
for item in a:
     for i in range(len(b)):
          if item == b[i]:
              c.append(b[i])

the answer should like this:

c = [[3,4],[1,2],[1,2]]

Simplest:

c = [b[i[0]] for i in a]

I recommend adding range checks though:

c = [b[i[0]] for i in a if (0 <= i[0] < len(b))]

EDIT: Based on your clarification of a , I recommend changing:

def findInstances(list1, list2):
    for i in list1:
        yield [pos for pos,j in enumerate(list2) if i==j] # This yields a list containing the value you want

to:

def findInstances(list1, list2):
    for i in list1:
        if (i in list2): 
            yield list2.index(i) # This yields only the value you want

This will flatten your list, and make the problem simpler. You can then use the following:

c = [b[i] for i in a if (0 <= i < len(b))]

Based on how you're getting a , the range checks are actually unnecessary. I left them in though, just in case you ever get a in a different way.

In [1]: a = [[1],[0],[0]]

In [2]: b = [[1,2],[3,4],[5,6]]

In [3]: [b[x[0]] for x in a] 
Out[3]: [[3, 4], [1, 2], [1, 2]]

using numpy indexing:

>>a = np.asarray(a)
>>b = np.asarray(b)
>>b[a]
array([[[3, 4]],

       [[1, 2]],

       [[1, 2]]])

Your algorithm is almost correct. The problem is with the if statement. If you tried print out item and b[i] before testing for equality you would see the problem.

>>> a = [[1],[0],[0]]
>>> b = [[1,2],[3,4],[5,6]]
>>> c = []
>>> for item in a:
>>>      for i in range(len(b)):
>>>           print("item == b[i] is {} == {} is {}".format(item, b[i], 
                      item == b[i]))
>>>           if item == b[i]:
>>>               c.append(b[i])
item == b[i] is [1] == [1, 2] is False
item == b[i] is [1] == [3, 4] is False
item == b[i] is [1] == [5, 6] is False
item == b[i] is [0] == [1, 2] is False
item == b[i] is [0] == [3, 4] is False
item == b[i] is [0] == [5, 6] is False
item == b[i] is [0] == [1, 2] is False
item == b[i] is [0] == [3, 4] is False
item == b[i] is [0] == [5, 6] is False

You have essentially been checking that each element in a and b for equality. Rather you want to check the elements in each item of a for equality with the index of b .

eg.

for item_a in a:
    for index_b, item_b in enumerate(b):
        # only check index 0 of item_a as all lists are of length one.
        print("item_a[0] == index_b is {} == {} is {}".format(item_a[0], 
                  index_b, item_a[0] == index_b))
        if item_a[0] == index_b:
            c.append(item_b)

produces:

item_a[0] == index_b is 1 == 0 is False
item_a[0] == index_b is 1 == 1 is True
item_a[0] == index_b is 1 == 2 is False
item_a[0] == index_b is 0 == 0 is True
item_a[0] == index_b is 0 == 1 is False
item_a[0] == index_b is 0 == 2 is False
item_a[0] == index_b is 0 == 0 is True
item_a[0] == index_b is 0 == 1 is False
item_a[0] == index_b is 0 == 2 is False

enumerate is a builtin helper function that returns a tuple containing the index and element for each element in a list (or anything that is iterable).

Unless you need to I would also recommend flattening a as having nested lists is redundant here ie. a = [1, 0, 0] .

Having said all this, if you can get your head around list comprehensions then coding a solution would be much simpler -- as evidenced by the other answers to your question.

this is how i comparing between another two different list.

def findInstances(list1, list2):
    for i in list1:
    yield [pos for pos,j in enumerate(list2) if i==j]


list1 = [0.1408, 0.1456, 0.2118, 0.2521, 0.1408, 0.2118]
list2 = [0.1408, 0.1456, 0.2118, 0.2521, 0.1254, 0.1243]
list3 = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
res = list(findInstances(list1, list2))

and res produce the output as 'a' in the first question

thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM