我正在尝试执行以下操作: -检查一个列表中的元素是否存在于另一列表中。如果是这样,则不执行任何操作,如果不执行此操作,则将其添加到该列表中。
简单的示例代码:
x=[1,2,3]
y=[2,3,4]
for item in x:
if item in y=='False':
y.append(item)
else:
continue
print(y)
不幸的是,它不起作用,作为一个初学者,我不确定为什么。有什么想法吗?
答案 0 :(得分:3)
您的代码不起作用的原因是该语句:
if item in y=='False':
检查条件的布尔答案
item in y
等于字符串'False'
,以触发 if
块。
根据您的问题,代码更正应为:
if item not in y:
y.append(item)
在上面的示例中,当 if
中有一个项目为 时,输入了 x
块。列表 y
答案 1 :(得分:0)
x=[1,2,3]
y=[2,3,4]
for item in x:
if item not in y:
y.append(item)
else:
continue
print(y)
礼物:
[2, 3, 4, 1]
答案 2 :(得分:0)
您应该使用:
x=[1,2,3]
y=[2,3,4]
for item in x:
if item not in y:
y.append(item)
else:
continue
print(y)
行:if item in y=='False':
永远不会为真,因为如果项不在y中,它将返回布尔值False,而不是字符串'False'