简体   繁体   English

for-else循环中的“else”是否存在反向行为?

[英]Is there an inverse behavior to the “else” in a for-else loop?

I have a for loop which tests for a condition. 我有一个for循环来测试一个条件。 I would like to execute some code if the condition was never met. 如果条件从未满足,我想执行一些代码。 The following code does the opposite: 以下代码恰恰相反:

a = [1, 2, 3]
for k in a:
    if k == 2:
        break
else:
    print("no match")

"no match" is printed if the break is not reached (for a condition like k == 10 for instance). 如果未达到break则打印“不匹配”(例如,对于k == 10的条件)。 Is there a construction which would do the opposite, ie run some code if the break is reached? 是否存在相反的结构,即如果达到break则运行一些代码?

I know I can do something like 我知道我可以做点什么

a = [1, 2, 3]
match = False
for k in a:
    if k == 2:
        match = True
if match:
    print("match")

but was looking for a more compact solution, without the flag variable.. 但正在寻找一个更紧凑的解决方案,没有标志变量..

Note : I now realize from the answers that I did not make it clear that I would like to move the "matched" code outside of the for loop. 注意 :我现在从答案中意识到我没有说清楚我想在for循环之外移动“匹配”代码。 It will be rather large and I would like to avoid hiding it in the for loop (thus the idea of the flag variable) 它会相当大,我想避免将它隐藏在for循环中(因此标志变量的想法)

If you put your condition inside of a function or a comprehension, you can use the any keyword to accomplish this in a very pythonic way. 如果您将条件置于函数或理解中,则可以使用any关键字以非常pythonic的方式完成此操作。

if not any(k == 2 for k in a):
    print 'no match'

If you were to move the condition to a function that returns a boolean, you could generalize this: 如果要将条件移动到返回布尔值的函数,则可以概括为:

def f(x):
    return x == 2

if not any(f(k) for k in a):
    print 'no match'

Sure. 当然。 Just put it before the break . break之前把它放好。

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("found")    # HERE
        break
else:
    print("no match")

Why not simply: 为什么不简单:

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("match")
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM