【问题标题】:Applying conditional after nested loop to the parent loop将嵌套循环后的条件应用于父循环
【发布时间】:2016-05-01 16:20:44
【问题描述】:

我有这个代码:

values="2"
content=["line1","line2","line3"]
for line in content:
    if values not in line:
        print(line)

当值 2 不在这些项目中时,它成功打印出 content 的项目:

line1
line3

实际上,我正在从 file.readlines() 方法中获取content

现在,当我必须将多个值与每个内容行进行比较时,我陷入了困境:

values=["2","3"]

再次,我需要检查 23 是否在每个 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。 有什么解决方法吗?

【问题讨论】:

  • 你不能用if not any(vv in line for vv in values)这样的东西吗?
  • 不应该 itemsvalues
  • 是的,应该。编辑问题以解决它。

标签: python loops if-statement nested-loops


【解决方案1】:

使用您在嵌套循环中设置的变量,并在循环完成后检查。

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)

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2019-11-07
    • 2011-04-23
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多