I am trying to find an easy way to do this:
list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
I want to get common elements of the two lists, with list1's order untouched, so this result is expected.
list3 = ['little','blue']
I am using
list3 = list(set(list1)&set(list2))
however, this only returns list3 = ['blue', 'little']
, obviously, set() just ignore the order.
You were almost there, just sort list3
according to list1
list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
list3 = set(list1)&set(list2) # we don't need to list3 to actually be a list
list4 = sorted(list3, key = lambda k : list1.index(k))
Result:
>>> list4
['little', 'blue']
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