python中的all()如何处理空列表 [英] How does all() in python work on empty lists
问题描述
我指的是下面的python代码
I am referring to the following python code
all(a==2 for a in my_list)
如果 my_list 中的所有元素都是 2,我希望上面的代码返回 True.但是当我将 my_list 设为空并将其作为
I expect the above code to return True if all the elements in my_list are 2. but when I make my_list empty and run it as
my_list = []
all(a==2 for a in my_list)
它也返回True.我对这种行为感到困惑.是否不应该返回 False,因为 my_list 中没有值为 2 的元素?
it returns True as well. I am confused with this behaviour. Is it not supposed to return False as there is no element in my_list with value 2?
推荐答案
这是真的,因为对于列表中的每个元素,它们都是 0,它们都等于 2.
It's true because for every element in the list, all 0 of them, they all are equal to 2.
你可以认为 all 被实现为:
You can think of all being implemented as:
def all(list, condition):
for a in list:
if not condition(a):
return false
return true
而 any 是:
def any(list, condition):
for a in list:
if condition(a):
return true
return false
也就是说,all
在被证明有罪之前都是无罪的,而any
在被证明无罪之前都是有罪的.
That is to say, all
is innocent until proven guilty, and any
is guilty until proven innocent.
这篇关于python中的all()如何处理空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!