我有这段代码:
values="2"
content=["line1","line2","line3"]
for line in content:
if values not in line:
print(line)
,当值content
不在这些项目中时,会成功打印2
项:
line1
line3
实际上,我从file.readlines()方法中抓取content
。
现在,当我必须针对每个内容行比较多个值时,我感到困惑:
values=["2","3"]
同样,我需要检查每个2
行中是3
还是content
,如果没有,则打印该行。
我想出了这个:
values=["2","3"]
content=["line1","line2","line3"]
for line in content:
for value in values:
if value not in line:
print(line)
但通常会回复:
line1
line1
line2
line3
我希望只打印line1
。
对此有任何解决方法吗?
答案 0 :(得分:2)
使用您在嵌套循环中设置的变量,并在循环完成后进行检查。
values=["2","3"]
content=["line1","line2","line3"]
for line in content:
in_line = false
for item in values:
if item in line:
in_line = true
break
if not in_line:
print(line)
或者您可以使用any
功能。
values=["2","3"]
content=["line1","line2","line3"]
for line in content:
if not any(value in line for value in values):
print(line)