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.我对此行为感到困惑.因为my_list中没有值2的元素,是否不应该返回False?
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.
您可以考虑将全部实施为:
def all(list, condition):
for a in list:
if not condition(a):
return false
return true
任何是:
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屋!