2013-08-16 52 views
3

我試圖找到一個簡單的方法來做到這一點:在Python中,如何從兩個列表中找到常用單詞,同時保留單詞順序?

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

我想這兩個列表的共同元素,用列表1的順序不變,所以這個結果的預期。

list3 = ['little','blue'] 

我使用

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

然而,這只是回報項目list3 = [ '藍', '小'],顯然,()設置忽略的順序。

任何幫助將不勝感激!

回答

3

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'] 
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'] 
+0

你先轉換列表2一組,因爲集更快地搜索,或者是還有另一個原因? – Brionius

+1

@Bionion,將'list2'轉換爲搜索速度。沒有其他原因。 – falsetru

+0

如果'list1 = ['little','blue','widget','little']'會怎麼樣?然後你的方法會產生'['小','藍','小']'。 – Akavall

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) 
+0

爲了記錄,列表理解方法比過濾方法快大約70%。 – Brionius

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'] 
你幾乎沒有,按照剛纔的排序 list3
相關問題