Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I find common words from two lists while preserving word order?

Tags:

python

list

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.

like image 203
michelle26 Avatar asked Aug 16 '13 01:08

michelle26


1 Answers

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']
like image 123
Akavall Avatar answered Oct 12 '22 14:10

Akavall