首页 > 解决方案 > 关于 all() 和 any() 函数的困惑

问题描述

我正在学习 python 并且在理解all()any()功能方面遇到了一些困惑:

1 in [0,2]             #False. Correct.
all([0,1]) in [0,2]    #True. Why? 1 is not in [0,2]
any([0,1]) in [0,2]    #False. Why? 0 is in [0,2]

标签: pythonsyntax

解决方案


如果可迭代对象中的所有项目都是并且如果有的话,函数all()返回布尔值:TrueTrueFalseFalse

all([0, 1]) # return True if all items are True

return Falsebecause0被认为是FalseFalse in [0, 2]返回时True,因为0 == False

为了any([0,1]) in [0,2] #False. Why? 0 is in [0,2]

any([0,1]) # return True if any item is True

返回True,因为1 = True.

然后它检查True in [0, 2]并没有Trueor 1in[0, 2]并返回False

In [1]: 1 == True                                                                                                                                                                                           
Out[1]: True

In [2]: 0 == False                                                                                                                                                                                          
Out[2]: True

In [3]: 2 == True                                                                                                                                                                                           
Out[3]: False

推荐阅读