gpt4 book ai didi

python - 为什么短路在 python 的 "all"函数中不起作用?

转载 作者:行者123 更新时间:2023-12-05 08:50:13 27 4
gpt4 key购买 nike

我正在尝试使用 python 的 all() 函数检查一些条件。

我的理解是这段代码会短路,一旦它评估条件为 False,该函数也会返回 False。如果这种理解是正确的,那么有人可以解释以下内容:

>>> a = None
>>> b = None
>>> all([a is None, b])
False
>>> all([a is None, b, "text" in b])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterable
>>> b = {"text": "Text I'm looking for"}
>>> all([a is None, b, "text" in b])
True

我第一次运行 all() 时显示它正确地评估为 False 那么为什么,如果我添加另一个测试,它会中断吗?我是否误解了短路的工作原理?

我已经在 python 3.8.3 和 python 2.7.18 中测试过,结果相同。

最佳答案

这与all 没有任何关系。您正在创建一个列表文字,它将在传递给 all 之前评估其内容:

>>> [a is None, b, "text" in b]

Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterables

如果您希望它按预期工作,您需要一个比列表更惰性的结构:

a = None
b = None

def lazy(): # A lazy generator
yield a is None
yield b
yield "text" in b

>>> all(lazy())
False

关于python - 为什么短路在 python 的 "all"函数中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62562863/

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