如何在for循环结束时执行命令?

rmp*_*150 2 python for-loop

我有以下代码

for x in list:
    if x.getValue == variableValue: 
        Print('Found')
Run Code Online (Sandbox Code Playgroud)

我想在循环的最后一次迭代中打印一条说"找不到匹配"的语句.

反正知道如果x当前正在运行通过for循环是最后xlist

msw*_*msw 6

for x in list:
    if x.getValue == variableValue: 
        print('Found')
        break
else:
    print('not found')
Run Code Online (Sandbox Code Playgroud)

for else也适用于只有在iterable(例如list)用尽且没有发生时子句运行的while else地方.elsebreak

有很多人发现这个结构让人难以理解,包括我自己.

  • -1,OP 明确指出即使找到了值,循环也需要继续。 (2认同)

Gar*_*tty 6

编辑:

更新的问题有一个简单的答案,没有.任意迭代器不知道它们是否在最后一个项目上,因此for循环无法知道.

也就是说,循环中的值不限于循环,因此x在循环结束后直接将始终是最后一个值.


如果您希望继续循环,只需设置一个标志:

found = False
for x in some_list:
    if x.value == value: 
        print('Found')
        found = True

if not found:
    print("Not Found.")
Run Code Online (Sandbox Code Playgroud)

如果你不想在循环的每一步上做某事,你可以使用any()生成器表达式来找出没有匹配的容易:

if not any(x.value == value for x in some_list):
    print("Not Found.")
Run Code Online (Sandbox Code Playgroud)