2017-05-22 86 views
1

我想查看列表中的項目是否與單獨列表中的另一項目匹配。Python查找另一個列表中的列表中的項目

然後我想要打印匹配的項目。

columns1= ['Dog', 'cat' , 'bird', 'fish'] 
columns2= ['Dog', 'CAT', 'bird', 'rat'] 

for col in columns1: 
    if col.upper() in [x.upper() for x in columns2]: 
     print(col, 'Matches with',) 
    else: 
     print(col, 'DOES NOT Match With Anything') 

電流輸出:

Dog Matches with 
cat Matches with 
bird Matches with 
fish DOES NOT Match With Anything 

所需的輸出:

Dog Matches with Dog 
cat Matches with CAT 
bird Matches with bird 
fish DOES NOT Match With Anything 

我使用list_name.index(string_here)試過,但隨後區分大小寫:

for col in columns1: 
    if col.upper() in [x.upper() for x in columns2]: 
     z = columns2.index(col) 
     print(col, 'Matches with', columns2[z]) 
    else: 
     print(col, 'DOES NOT Match With') 

output: 
Dog Matches with Dog 
ValueError: 'cat' is not in list 

我可以創建一個單獨的列表,將列表中的所有內容都大寫,但我覺得這是一種欺騙行爲,如果數據集非常大,則會產生不必要的性能提升。

解決此問題的更好方法是什麼?

+0

可以列表是'columns1 = [ '狗', '貓', '鳥', '魚'] columns2 = [ '貓' 狗 ''鳥','老鼠']' –

+0

是的,它們可能不匹配 – MattR

+0

您預計「非常大的數據集」存在多少項? –

回答

4

我認爲性能問題就在這裏,你在從列表中搜索。這是線性搜索這是O(n)。如果您將值存儲在字典中。那麼平均查找時間將是O(1),這是更快的方式。此外,str.upper()將只被稱爲每個項目

所以,你先準備一本字典:

lookup = {k.upper():k for k in columns2} 

接下來我們可以使用:

for col in columns1: 
    result = lookup.get(col.upper()) 
    if result is not None: 
     print(col, 'Matches with', result) 
    else: 
     print(col, 'DOES NOT Match With')

如果col.upper()在字典中的lookup.get(..)方法查找(注意,在字典中的鍵也以大寫字母)。如果是在字典result將相應的原始值columns2。如果不是None將被退回。因此,我們只需檢查None以瞭解查找是否成功。

這會產生:?

Dog Matches with Dog 
cat Matches with CAT 
bird Matches with bird 
fish DOES NOT Match With 
+0

這其實很棒。由於他們的表現,我考慮過字典,但想不到一個辦法。謝謝! – MattR

相關問題