Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: compare two lists and return matches in order

Tags:

python

list

set

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

like image 302
Boosted_d16 Avatar asked Dec 08 '22 05:12

Boosted_d16


2 Answers

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']
like image 140
Ashwini Chaudhary Avatar answered Dec 11 '22 10:12

Ashwini Chaudhary


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']
like image 32
Hackaholic Avatar answered Dec 11 '22 08:12

Hackaholic