在Python中是否将any()或all()与break语句逻辑一起使用?

2024-09-30 06:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这项工作:

def gen():
    yield False
    yield True
    yield oups

if any(gen()):
    print('At least one is True')

# At least one is True

但这失败了:

if any(iter([False, True, oups])):
    print('At least one is True')

# NameError: name 'oups' is not defined

有没有一种方法可以不费吹灰之力地将第二个代码转换成第一个代码


Tags: 代码falsetrueifisdefanyone
2条回答

这两段代码在技术上都不正确,因为您没有定义“oups”。
这可以通过耗尽迭代器来显示,如下所示:

def gen():
    yield False
    yield True
    yield oups

g = gen()
print(next(g))
print(next(g))
#this next line will break, as it reaches the undefined variable
print(next(g))  

any()函数在命中第一条True语句后将停止运行,并返回True。这可以通过重新排列收益率语句,使未定义变量后的第一个True来显示,这也将中断:

def gen():
    yield False
    yield oups
    yield True

if any(gen()):
    print('At least one is True')

对于genoups只是一个自由变量,它的查找从未发生过any在需要之前停止使用由gen返回的生成器

但是,对于iter([False, True, oups]),必须首先完全创建列表[False, True, oups],以便将其传递给iter以返回列表迭代器。要执行,必须进行oups的查找,因为它没有定义,我们在iter之前得到一个NameError,更不用说any甚至运行了。第二个代码的计算方法与

t1 = [False, True, oups]  # NameError here
t2 = iter(t1)
if any(t2):
    print('At least one is True')

相关问题 更多 >

    热门问题