为什么 Python 内置"all"函数为空可迭代对象返回 True?



我知道它有一个很好的理由,但我想知道是什么原因?

>>> print all([])
True

如果 all() 旨在检查可迭代表上的每个项目是否都计算为 "True",并且我们知道空列表的计算结果为 False

>>> bool([])
False

那么为什么 all() 为空列表返回 True?

<编辑>

我已经阅读了文档,并且我知道实现

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

但问题是为什么不呢?

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

这有什么逻辑吗? 如果你有一个已完成的任务列表

today_todo_status = [task.status for task in my_todo if task.date == today]
can_i_go_home = all(today_todo_status)

好的,在上面的假设例子中,如果我没有任务,这真的很有意义,所以我可以回家了。

但是还有其他情况,我不认为 all() 是为待办事项列表制作的。大声笑

表示为"对于S中的所有X,X为真"。如果 S 为空,则没有 X。然而,真理陈述仍然是真的,因为对于所有X,X都是真的......只是没有X!

这是使用逻辑的解释。

考虑两个集合 A 和 B,其中 A+B 是两个集合的并集。

如果 any(A+B) = True -> any(A) 或 any(B) = True,但我们不能断言any(A)=True或any(B)=True。

如果 any(A+B) = False ->any(A) = False 和 any(B) = False。

如果 all(A+B) = True ->则 all(A)=True 且 all(B)=True

如果 all(A+B) = False -> all(A)=False 或 all(B)=False,

但我们不能断言 all(A)=False 或 all(B)=False。

现在让我们将

空集 Ø 添加到 A 而不是 B。我们想上来逻辑,使得添加空集不会更改all() 或 any(),因为 A+Ø=A。

any(A+Ø) = any(A) or any(Ø)

any(Ø) 必须为 False,因此如果 any(A) 为 True,any(A+Ø) 为 True,并且如果 any(A) 为 False,则 any(A+Ø) 为 False。

all(A+Ø) = all(A) 和 all(Ø)

如果 all(A) 为 True,则 all(A+Ø) 为 True。因此,all(Ø) 为真。

all()(记录为"如果可迭代对象的所有元素都为真(或者如果可迭代对象为空)则返回 True")。 等效于以下内容:

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

由于没有元素,它将跳过循环并返回True

这来自数理逻辑。

"空集的元素一切都是真实的"(http://en.wikipedia.org/wiki/Empty_set)

另请参阅 http://en.wikipedia.org/wiki/Vacuous_truth

假设all([])False

然后,对于所有非空列表Aall(A + [])也应该False

all(A + []) = all(A) and all([])
            = all(A) and False
            = False

A + [] = A年以来,我们知道

all(A + []) = all(A) for any non empty list A

但是,all(A)可能是True(例如,A = [True]

因此

对于所有非空列表Aall(A + [])也应该False

这是矛盾的。结果,第一个假设是错误的,并且

all([]) True

因为所有元素都是 True。当没有元素时,你可以说'所有元素都是......什么都行'

ELI5 版本。

列出数字

L = [1,2,3,4,6]
all([isintance(l, int) for l in L])

all的定义方式是,使其False的唯一方法是提供一个非整数at least

类似地,any的定义方式是,要使其True您所需要的只是at-least一个正整数。

既然all()any()的补充,那么一个必须是True的,另一个必须是False

在测试条件时,我们希望始终将第一个元素添加到列表中。 例如,如果我们只想将小于最小数字或大于最大数字的数字添加到列表中,我们可以这样做:

def addToList(less,num):
    if less:
        if any( num >= savedNum for savedNum in numbers):
            print('{} is not less'.format(num))
            return
    elif any( num <= savedNum for savedNum in numbers):
        print('{} is not greater'.format(num))
        return
    numbers.append(num)

numbers = []
doLess = True
doMore = False
addToList(doLess,5) #numbers is empty, but will be added
addToList(doLess,2)
addToList(doLess,7)
addToList(doMore,15)
addToList(doMore,9)
print(numbers)

输出:

7 is not less [5, 2]
9 is not greater [5, 2, 15]
[5, 2, 15]

最新更新