如何让我的其他打印只打印一次而不是每行不存在?我尝试通过回击几层来移动它,但它不起作用。我理解逻辑,但我不知道如何限制它。我一点一点地添加到我的解析脚本中进行练习,随时学习,但是这个让我感到高兴。谢谢!
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!"
答案 0 :(得分:5)
在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子句。
答案 1 :(得分:3)
首先看Gibson的回答。你可以这样做:
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çoisFabre建议),但这有点难以理解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!"