是否所有(列表)都使用短路评估? [英] Does all(list) use short circuit evaluation?

查看:70
本文介绍了是否所有(列表)都使用短路评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用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 returns False, then the function immediately breaks.

这篇关于是否所有(列表)都使用短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆