python - any() 是否被延迟评估?

标签 python

我正在编写一个脚本,其中我必须根据多种条件测试数字。如果满足任何条件,我想返回True,并且我想以最快的方式返回。

我的第一个想法是使用 any() 而不是嵌套的 if 语句或多个 or 链接我的条件。因为如果任何条件为 True 我会很满意,所以我可以真正受益于 any() 的惰性并尽快返回 True。

基于以下打印立即发生而不是在 10 (= 0 + 1 + 2 + 3 + 4) 秒后发生的事实,我认为它是。是这样还是我搞错了?

import time

def some(sec):
    time.sleep(sec)
    return True

print(any(some(x) for x in range(5)))

最佳答案

是的,any()all() 短路,结果一明确就中止:参见 docs :

all(iterable)

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

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

关于python - any() 是否被延迟评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348588/

相关文章:

python - 消费完所有消息后如何关闭kafka消费者?

python - 使用 Python 和 Mechanize 以随机形式填充

python - 如何关闭 Python/Selenium 中的麦克风/摄像头弹出窗口?

python - Python 社区里的小马是怎么回事?

python - 当不存在此类数据时,是否可以使用 python 将 IPTC 数据添加到 JPG?

python - 在 python 中通过 hotmail 发送电子邮件

python - 如何将张量元素划分为特定索引

Python 2.7 : Code won't return answer - someone explain why?

Python isinstance() 的 float 失败断言测试

python - 了解交叉熵损失