在Python中,如何在保留单词顺序的同时从两个列表中找到常用单词?

时间:2013-08-16 01:33:54

标签: python list

我正在努力寻找一种简单的方法:

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

我希望得到两个列表的共同元素,其中list1&#39的顺序不变,因此预期会出现此结果。

list3 = ['little','blue']

我正在使用

list3 = list(set(list1)&set(list2))

然而,这只返回list3 = [' blue',' little'],显然,set()只是忽略了订单。

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:5)

你几乎就在那里,只根据list3

排序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))

结果:

>>> list4
['little', 'blue']

答案 1 :(得分:4)

使用列表理解:

>>> list1 = ['little','blue','widget']
>>> list2 = ['there','is','a','little','blue','cup','on','the','table']
>>> s = set(list2)
>>> list3 = [x for x in list1 if x in s]
>>> list3
['little', 'blue']

答案 2 :(得分:0)

以下是使用过滤器的实现:

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
set2 = set(list2)
f = lambda x:x in set2

list3 = filter(f, list1)

答案 3 :(得分:0)

这就是你要求使用python 2.7,不是特别优雅,但它确实回答了你的问题。

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
list3 = []
for l1 in list1:
    for l2 in list2:
        if l2 == l1:
            list3.append(l2)

print list3  # ['little', 'blue']