【问题标题】:Unexpected results when converting while loop to for loop将while循环转换为for循环时出现意外结果
【发布时间】:2018-01-10 00:14:48
【问题描述】:

我有一个通常运行良好的 while 循环,但我想将其转换为 for 循环。 while循环如下:

with open(filename) as a:
while tally != c:
    line = a.readline()
    c = line.strip()

在我打开文件的地方,读取每一行,直到找到我感兴趣的行。for循环如下:

with open(filename) as a:
for line in enumerate (a):
    if tally == c:
        break
    elif tally != c:
        c = line

看起来循环每次都只是读取到文件末尾,并将变量c 转换为一个由随机数和文件最后一行组成的元组。我知道 tally 中包含的字符串存在于文件中,因为 while 循环执行了预期的功能。

【问题讨论】:

  • c = linec = line.strip() 不同。
  • 另外,for line in a,而不是 for line in enumerate(a)
  • 我认为问题中代码中的缩进问题只是复制/粘贴中引入的错误。
  • 绝对是缩进的复制/粘贴问题。如果这是问题所在,那将是一个巨大的尴尬!

标签: python-2.7 loops for-loop while-loop


【解决方案1】:

固定代码:

with open(filename) as a:
    for line in a:
        if tally == c:
            break
        else:
            c = line.strip()

两个问题:

  1. for line in enumerate(a) 表示line 在每次迭代行号和文件中的实际行时获取一个元组。阅读 enumerate 以了解其用途。
  2. c = line 与原始循环中的 c = line.strip() 不同。

【讨论】:

  • 现在我从中提取“枚举”的文件也更有意义了,谢谢!
【解决方案2】:

必须是c=line.strip(),而不是c=line

【讨论】:

  • 对不起!正如 smarx line.strip() 所回答的,必须使用。我已经编辑了我的答案。
猜你喜欢
  • 2018-02-22
  • 2017-04-26
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2020-06-20
相关资源
最近更新 更多