这项工作:
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:
这两段代码在技术上都不正确,因为您没有定义“oups”。
这可以通过耗尽迭代器来显示,如下所示:
any()函数在命中第一条True语句后将停止运行,并返回True。这可以通过重新排列收益率语句,使未定义变量后的第一个True来显示,这也将中断:
对于
gen
,oups
只是一个自由变量,它的查找从未发生过any
在需要之前停止使用由gen
返回的生成器但是,对于
iter([False, True, oups])
,必须首先完全创建列表[False, True, oups]
,以便将其传递给iter
以返回列表迭代器。要执行这,必须进行oups
的查找,因为它没有定义,我们在iter
之前得到一个NameError
,更不用说any
甚至运行了。第二个代码的计算方法与相关问题 更多 >
编程相关推荐