簡體   English   中英

如何比較兩個字符串列表並返回匹配項

[英]How to compare two lists of strings and return the matches

我有這個問題作為家庭作業,我無法弄清楚。

您有 2 個包含您選擇的內容的字符串列表。 使用循環遍歷列表並比較列表元素並僅顯示重復的列表元素(該元素存在於兩個列表中)。 即使其中一個使用大寫而另一個使用小寫或它們的組合,也應顯示字符串。

我不知道為什么它不起作用。

animals = ["dog", "bear", "monkey", "bird"]
pets = ["dog", "bird", "cat", "snake"]

print("The original list 1 : " + str(animals))
print("The original list 2 : " + str(pets))

res = [animals.index(i) for i in pets]

print("The Match indices list is : " + str(res))

也許這就是你正在尋找的。

l1 = ["asd", "dfs", "anv"]
l2 = ["asds", "dfs", "anv"]
temp = [x for x in l1 if x in l2]
print(temp)

在比較兩個字符串時使用 if 語句。

最好檢查字典或集合成員,而不是使用 list.index。

字典查找是一個 O(1) 操作,而list.indexx in list ( list.__contains__ ) 是 O(n)。

您可以構建一個字典,其中名稱 map 到輸入列表中的索引。

>>> animals = ["dog", "bear", "monkey", "bird"]
>>> pets = ["dog", "bird", "cat", "snake"]
>>> animals_mapping = {name.lower(): idx for idx, name in enumerate(animals)}
>>> animals_mapping
{'dog': 0, 'bear': 1, 'monkey': 2, 'bird': 3}

>>> [animals_mapping.get(name.lower(), -1) for name in pets]
[0, 3, -1, -1]

試試這個(又快又臟):

animals = ["dog", "bear", "monkey", "bird"]
pets = ["dog", "bird", "cat", "snake"]

print("The original list 1 : " + str(animals))
print("The original list 2 : " + str(pets))
res = []
for a in animals:
    for p in pets:
        if a == p:
            res.append(a)


print("The Match indices list is : " + str(res))

我對您的代碼進行了一些更新,以便它適應具有不同大小寫(大寫/小寫)的相似元素

animals = ["dOg", "bear", "monkey", "bIrd"]
pets = ["doG", "Bird", "cat", "snake"]

for x in range(len(pets)):
    pets[x] = pets[x].lower()

match = [x.lower() for x in animals if x.lower() in pets]
print("The original list 1 : " + str(animals))
print("The original list 2 : " + str(pets))
print("matched element(s) in both lists: ", match)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM