是否所有(列表)都使用短路评估? [英] Does all(list) use short circuit evaluation?
问题描述
我希望使用Python all()
函数来帮助我计算某些东西,但是如果all()
击中False
时不立即求值,那么这件事可能会花费更长的时间.我认为这可能是经过短路评估的,但我只是想确定一下.另外,有没有一种方法可以在Python中说明该函数的求值方式?
I wish to use the Python all()
function to help me compute something, but this something could take substantially longer if the all()
does not evaluate as soon as it hits a False
. I'm thinking it probably is short-circuit evaluated, but I just wanted to make sure. Also, is there a way to tell in Python how the function gets evaluated?
推荐答案
是的,它会短路:
>>> def test():
... yield True
... print('one')
... yield False
... print('two')
... yield True
... print('three')
...
>>> all(test())
one
False
从文档:
如果iterable的所有元素都为true(或者iterable为空),则返回True.等同于:
From the docs:
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
因此,当return
为False时,该函数将立即中断.
So when it return
s False, then the function immediately breaks.
这篇关于是否所有(列表)都使用短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!