Python中all()和bool()的空情况?

4 投票
4 回答
507 浏览
提问于 2025-04-18 11:07

当你使用 help(all) 时,它会返回:

all(iterable)=>bool
return True if bool(x) is True for all values x in the iterable.    
if the iterable is empty, return True

help(bool) 返回:

bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.

当你尝试:

>>>bool()
False

>>>all([])
True

我的问题是,如果 all 的输入是空列表、空字典或空元组(也就是迭代器),那么传给 bool 的是什么呢?为什么它会返回 True,因为这取决于 bool?

4 个回答

2

我猜这个实现大概是这样的:

def all(inp):
    return not any(not bool(x) for x in inp)

所以一个空的迭代器被认为是“空真”。这个说法是有道理的,也和逻辑中的一些概念相符——我们通常会说,即使存在某个命题不成立,但在某个范围内,普遍量词仍然成立。

6

[…] 传给 bool 的是什么?

什么都没有——而且这里的“什么都没有”不是指 bool() 的“什么都没有”。其实 bool 从来没有被调用过。那空序列里的每个元素都是“真实”的(truthy)吗?是的!因为根本就没有元素不真实。

7
all(iterable)

...在这里有个文档说明,它的意思是;

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

...这个函数会返回 只有当列表中的任何一个值转换为 False 时,它才会返回 False

因为你传入的列表里没有任何元素,所以没有元素会转换为 False,因此这个函数的结果是 True。

13

bool() 这个函数在 all() 的参数是空的时候根本不会被调用。这就是为什么文档特别提到 all() 在空输入时的行为是个特例。

bool() == False 这个行为和 all() 的功能没有关系。顺便说一下,在 Python 中,boolint 的一个子类,所以 bool() == False 是为了和 int() == 0 保持一致。

至于为什么像 all([]) 这样的结果是 True,这是为了保持一些有用的特性。最重要的是,对于任何非空的序列 x,我们希望有

all(x) == (bool(x[0]) and all(x[1:]))

all([]) == True 是唯一一个能让这个特性对所有 x 的值都成立的结果。

撰写回答