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
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With