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

时间:2017-03-09 02:13:29

标签: python

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

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

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

根据Grus的说法,Python将[](一个空列表)视为“虚假”参数。那么为什么我们会根据all()any()参数是否应用于空列表来获得不同的结果?

2 个答案:

答案 0 :(得分:2)

the documentation of all

  

<强> all(iterable)

     

如果iterable的所有元素都为true (或者如果iterable为空),则返回True

documentation for any

  

<强> any(iterable)

     

如果iterable的任何元素为true,则返回True如果iterable为空,请返回False

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

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

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

由于这个特定的实现,如果iterable为空,则完全跳过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可以被认为是&#34;与元素一样多的真元素&#34;。由于空集没有真元素而没有元素,因此返回true,因为0等于0. any可以被认为是&#34;至少有一个......&#34;,并且因为集合是空的,所以至少没有一个,因为甚至没有一个元素。因此all对于空集返回true,而any对于空集返回false。

答案 1 :(得分:1)

这个定义背后的逻辑推理如下:

any存在量词相关,而all通用量词相关,并遵循其逻辑规范。

any翻译为至少有一个[]的至少一个元素评估为true&lt; - NO。

请参阅https://math.stackexchange.com/questions/281735/quantification-over-the-empty-sethttps://math.stackexchange.com/questions/202452/why-is-predicate-all-as-in-allset-true-if-the-set-is-empty -

相关问题