python - 为什么空列表中的任何一个和所有都返回不同的东西?

标签 python

的第2章Data Science from Scratch 由 Joel Grus 提供,提供了以下示例:

all([ ]) # True, no falsy elements in the list

any([ ]) # False, no truthy elements in the list

根据 Grus 的说法,Python 将 [] (空列表)视为“错误”参数。那么为什么根据 all()any() 参数应用于空列表会得到不同的结果呢?

最佳答案

the documentation of all :

all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty).

还有documentation for any :

any(iterable)

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

空的可迭代[]是错误的,但这并不重要,因为返回值只是通过实现实现的。

<小时/>

如果您想知道为什么会发生这种情况,这只是实现的结果。如果您从文档中查看 all 的等效代码:

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

由于这种特定的实现,如果可迭代为空,则完全跳过 for 循环,因为没有元素。因此,它返回True。对于any,文档提供了等效的代码:

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

它为空迭代返回 False 的原因与 all 返回 True 的原因相同。由于列表中没有元素,因此将跳过 for 循环并返回 False

此实现确实有一个推理,因为空集逻辑使 all 返回 true,请参阅 this Math.SE postthis SO answerall 可以被认为是“有与元素一样多的真实元素”。由于空集合没有 true 元素,也没有元素,因此它返回 true,因为 0 等于 0。any 可以被认为是“至少有一个...”,并且由于集合是空的,至少没有一个,因为甚至没有一个元素。因此,对于空集,all 返回 true,对于空集,any 返回 false。

关于python - 为什么空列表中的任何一个和所有都返回不同的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685428/

相关文章:

python - 匹配列表中的任何关键字是否存在于字符串中

python - 使用 matplotlib 设置或 Hook 双变量分布值

python - Pandas :应用返回 list

python - 比较大型数据库

python - pandas - 在 DataFrame 中搜索字符

python - 删除变量中的变量

python - 在 Python 中制作 pandas.DatetimeIndex 的有效方法

python - 有没有办法从音频文件中删除/编辑名为 "tag"的元数据条目,而无需安装任何其他内容?

python - 分类指标无法处理二进制目标和连续目标的混合

python - 从 python 运行另一个程序