gpt4 book ai didi

Python 检查项目是否在列表中

转载 作者:行者123 更新时间:2023-11-28 18:20:55 25 4
gpt4 key购买 nike

我正在尝试遍历两个列表并检查 list_1 中的项目是否在 list_2 中。如果 list_1 中的项目在 list_2 中,我想打印 list_2 中的项目。如果该项目不在 list_2 中,我想打印 list_1 中的项目。下面的代码部分地完成了这个,但是因为我正在执行两个 for 循环,所以我得到了 list_1 的重复值。你能指导我用 Pythonic 的方式完成吗?

list_1 = ['A', 'B', 'C', 'D', 'Y', 'Z']
list_2 = ['Letter A',
'Letter C',
'Letter D',
'Letter H',
'Letter I',
'Letter Z']

for i in list_1:
for x in list_2:
if i in x:
print(x)
else:
print(i)

当前输出:

Letter A
A
A
A
A
A
B
B
B
B
B
B
C
Letter C
C
C
C
C
D
D
Letter D
D
D
D
Y
Y
Y
Y
Y
Y
Z
Z
Z
Z
Z
Letter Z

期望的输出:

Letter A
B
Letter C
Letter D
Y
Letter Z

最佳答案

你可以这样写:

for i in list_1:
found = False
for x in list_2:
if i in x:
found = True
break
if found:
print(x)
else:
print(i)

上述方法确保您打印 xi 并且我们只为 list_1 中的每个元素打印一个值。

你也可以写(这和上面的一样,但是利用了将 else 添加到 for 循环的能力):

for i in list_1:
for x in list_2:
if i in x:
print(x)
break
else:
print(i)

关于Python 检查项目是否在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45130303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com