我正在尝试迭代两个列表并检查 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)
上述方法确保您打印x
or i
我们只打印每个元素的一个值list_1
.
您也可以编写(与上面的内容相同,但利用了添加else
to a for
loop):
for i in list_1:
for x in list_2:
if i in x:
print(x)
break
else:
print(i)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)