【问题标题】:Print else only once? [duplicate]只打印一次? [复制]
【发布时间】:2018-03-27 11:10:32
【问题描述】:

如何让我的 else 打印只打印一次,而不是为字符串不存在的每一行打印?我尝试通过向后拉几层来移动它,但它不起作用。我理解逻辑,但我不知道如何限制它。我一次添加一点到我的解析脚本中进行练习,边学习边学习,但是这个让我受益匪浅。谢谢!

import csv
# Testing finding something specifical in a CSV, with and else
testpath = 'C:\Users\Devin\Downloads\users.csv'
developer = "devin"

with open (testpath, 'r') as testf:
    testr = csv.reader(testf)
    for row in testr:
        for field in row:
            if developer in row:
                print row
        else:
            print developer +  " does not exist!"

【问题讨论】:

  • 在你的代码中应该是if developer in field: 吗? (不是in row:)?

标签: python python-2.7 csv parsing for-loop


【解决方案1】:

在 Python 中,您可以将 else 子句附加到您的 for 循环。例如

>>> for i in range(10):
...     if i == 5: break # this causes the else statement to be skipped
... else:
...     print 'not found'
...

注意5被发现所以不执行else语句

>>> for i in range(10):
...     if i == 15: break
... else:
...     print 'not found'
...
not found

documentation on for statements

在第一个套件中执行的 break 语句终止循环 不执行 else 子句的套件。继续声明 在第一个套件中执行会跳过套件的其余部分并继续 使用下一项,如果没有下一项,则使用 else 子句。

【讨论】:

  • 多么有价值的信息。从来不知道这个!
  • Raymond Hettinger 建议引入nobreak 关键字,但该提案从未通过...更多here
  • @mentalita 感谢您的链接。我同意它的当前实现有点混乱
  • 谢谢@PeterGibson!休息是我一直在寻找的,有道理。我想知道为什么我的问题被否决了,他们声称回答了我的问题的帖子没有回答我的问题......
【解决方案2】:

先看吉布森的回答。你可以这样做:

for row in testr:
    found = False
    for field in row:
        if developer in row:
            print row
            found = True
            break
    if found: break
else:
    print developer +  " does not exist!"

您也可以省略 found 标志(正如评论中 Jean-François Fabre 所建议的那样),但这使得 imo 有点难以理解(我不得不在脑海中编译):

for row in testr:       
    for field in row:
        if developer in row:
            print row
            # We found the developer. break from the inner loop.
            break
    else:
        # This means, the inner loop ran fully, developer was not found.
        # But, we have other rows; we need to find more.
        continue
    # This means, the else part of the inner loop did not execute.
    # And that indicates, developer was found. break from the outer loop.
    break
else:
    # The outer loop ran fully and was not broken
    # This means, developer was not found.
    print developer, "does not exist!"

【讨论】:

  • found 标志没有用。您也可以在内循环中使用else 技巧。
  • 是的。答案已更新。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-03-31
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 2018-12-25
相关资源
最近更新 更多