我想查看列表中的項目是否與單獨列表中的另一項目匹配。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
我可以創建一個單獨的列表,將列表中的所有內容都大寫,但我覺得這是一種欺騙行爲,如果數據集非常大,則會產生不必要的性能提升。
解決此問題的更好方法是什麼?
可以列表是'columns1 = [ '狗', '貓', '鳥', '魚'] columns2 = [ '貓' 狗 ''鳥','老鼠']' –
是的,它們可能不匹配 – MattR
您預計「非常大的數據集」存在多少項? –