[英]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.index
或x 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.