【问题标题】:Nested For loop Iteration嵌套 For 循环迭代
【发布时间】:2019-06-01 02:46:52
【问题描述】:

我是 python 新手,我试图打开一个文件并打印一个匹配两个值的行(一个来自列表的值,第二个值是静态值)。我得到了第一次迭代的预期输出,但看起来 for 循环没有运行任何其他迭代。

下面是代码:

text_file = open(Path, 'r')
list_1 = ['One', 'Two', 'Three']
static_value = 'Test'

for term in list_1:
    for line in text_file:
        if term in line and static_value in line:
            print(line)

文件内容示例:

一个

一次测试

两个

两个测试

三个

三试

【问题讨论】:

  • 请向我们展示您的文本文件的内容。谢谢。
  • 您只能对打开的文件进行一次迭代。您必须为每个循环重新打开它
  • 一旦到达文件末尾,文件中就没有更多行可以循环了。 seek() 回到文件开头,或者交换循环:for line in text_file: for term in list_1: :`
  • stackoverflow.com/q/54862214/1848654 的可能副本(唯一的问题是它使用完全不同的编程语言)。
  • 感谢大家的快速回复。交换 for 循环就可以了。还将查看 seek()

标签: python for-loop


【解决方案1】:

如果你交换你的for 循环是可能的。更优雅的方法是使用any() 来检查匹配,如下所示:

for line in text_file:
    if any(term in line for term in list_1) and static_value in line:
        print(line)

【讨论】:

  • 感谢您的回复。交换 for 循环就可以了。到目前为止我没有使用any()函数,我将研究any()函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多