gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:00:29 27 4
gpt4 key购买 nike

我正在编写一个脚本,其中我必须根据多种条件测试数字。如果满足任何条件,我想返回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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com