我試圖找到一個簡單的方法來做到這一點:在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 = [ '藍', '小'],顯然,()設置忽略的順序。
任何幫助將不勝感激!
你先轉換列表2一組,因爲集更快地搜索,或者是還有另一個原因? – Brionius
@Bionion,將'list2'轉換爲搜索速度。沒有其他原因。 – falsetru
如果'list1 = ['little','blue','widget','little']'會怎麼樣?然後你的方法會產生'['小','藍','小']'。 – Akavall