python: compare two lists and return matches in order

10,847

Solution 1

Convert b to a set and then loop over a's items and check if they exist in that set:

>>> s = set(b)
>>> [x for x in a if x in s]
['a', 'd']

Solution 2

you need to use set:

>>> a = ['a','s','d','f']
>>> b = ['e','d','y','a','t','v']
>>> sorted(set(a) & set(b), key=a.index) # here sorting is done on the index of a
['a', 'd']

Solution 3

a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
st_b = set(b)
print([ele for ele in a if ele in st_b])
['a', 'd']

Solution 4

a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
matches=[]
for item_a in a:
    for item_b in b:
        if item_a == item_b:
            matches.append(item_a)
print(matches)
Share:
10,847
Boosted_d16
Author by

Boosted_d16

Python and PowerPoints. The 2 most important Ps in the world.

Updated on June 19, 2022

Comments

  • Boosted_d16
    Boosted_d16 almost 2 years

    I have two lists of unequal length and I would like to compare and pull matched values in the order from the first list, so a in this example.

    a = ['a','s','d','f']
    b = ['e','d','y','a','t','v']
    

    expected output:

    ['a','d']
    

    I was doing it like this but I forgot that set doesnt retain the order! how can I edit my code below to retain the order.

     set(a).intersection(b)
    

    Linked to this How can I compare two lists in python and return matches

  • Matthias
    Matthias over 9 years
    What if a = ['a','s','d','a']?
  • Matthias
    Matthias over 9 years
    I would expect ['a', 'd', 'a'] but the question might be academic.