gpt4 book ai didi

python - Python的reduce()会短路吗?

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

如果我这样做:

result = reduce(operator.and_, [False] * 1000)

它会在第一个结果后停止吗? (因为 False & anything == False)

类似地:

result = reduce(operator.or_, [True] * 1000)

最佳答案

事实并非如此。在这种情况下,您的替代方案是 anyall .

result = reduce(operator.and_, [False] * 1000)
result = reduce(operator.or_, [True] * 1000)

可以替换为

result = all([False] * 1000)
result = any([True] * 1000)

短路。

计时结果显示差异:

In [1]: import operator

In [2]: timeit result = reduce(operator.and_, [False] * 1000)
10000 loops, best of 3: 113 us per loop

In [3]: timeit result = all([False] * 1000)
100000 loops, best of 3: 5.59 us per loop

In [4]: timeit result = reduce(operator.or_, [True] * 1000)
10000 loops, best of 3: 113 us per loop

In [5]: timeit result = any([True] * 1000)
100000 loops, best of 3: 5.49 us per loop

关于python - Python的reduce()会短路吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3570624/

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