如何比较两个字符串列表并返回匹配项

2024-06-17 10:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题是我的家庭作业,我想不出来

您有两个字符串列表,其中包含您选择的内容。 使用循环遍历列表并比较列表元素,并仅显示重复的列表元素(两个列表中都存在该元素)。应显示字符串,即使其中一个使用大写,另一个使用小写或其组合

我不知道为什么它不起作用

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))

Tags: the字符串元素内容列表reslistprint
3条回答

试试这个(又快又脏):

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)

也许这就是你一直在寻找的

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

比较两个字符串时要使用If语句

相关问题 更多 >