[英]How to compare two lists of strings and return the matches
I have this question as homework and I can't figure it out.我有这个问题作为家庭作业,我无法弄清楚。
You have 2 lists of strings with contents of your choice.您有 2 个包含您选择的内容的字符串列表。 Use a loop that goes through the lists and compares the lists elements and displays only the list elements that duplicate (the element exists in both lists).
使用循环遍历列表并比较列表元素并仅显示重复的列表元素(该元素存在于两个列表中)。 The strings should be displayed even if in one is used uppercase and in the other lowercase or a combination of it.
即使其中一个使用大写而另一个使用小写或它们的组合,也应显示字符串。
I don't know why it's not working.我不知道为什么它不起作用。
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))
Maybe this is what you were searching for.也许这就是你正在寻找的。
l1 = ["asd", "dfs", "anv"]
l2 = ["asds", "dfs", "anv"]
temp = [x for x in l1 if x in l2]
print(temp)
If statements are to be used when comparing between two strings.在比较两个字符串时使用 if 语句。
It's better to check for dictionary or set membership, than using list.index.最好检查字典或集合成员,而不是使用 list.index。
Dictionary lookup is a O(1) operation, compared to list.index
or x in list
( list.__contains__
) which is O(n).字典查找是一个 O(1) 操作,而
list.index
或x in list
( list.__contains__
) 是 O(n)。
You can construct a dictionary where the names map to the index in the input list.您可以构建一个字典,其中名称 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]
Try this (quick and dirty):试试这个(又快又脏):
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))
I updated your code a bit so that it caters to similar elements with different casings (uppercase/lowercase)我对您的代码进行了一些更新,以便它适应具有不同大小写(大写/小写)的相似元素
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.