我正在学习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]
all([0,1])
返回False
(因为0的“真实性”被定义为False
)并且False in [0,2]
返回True
(出于非常相似的原因)。
可能你打算说些什么
any(x in [0,1] for x in [0,2]) # True
all(x in [0,1] for x in [0,2]) # False
你误解了你的表达式是如何计算的。首先,请注意0
是假的,1
是真的。 all([0,1])
是False
,因为并非所有元素都是真实的。 any([0,1])
是True
,因为有些元素是真实的。然后你在False
寻找True
和[0, 2]
的会员资格。当作为数字时,True
的值为1
,而False
的值为0
。因此,False in [0, 2]
评估为True
因为False == 0
是True
,所以False
在[0, 2]
“被发现”。以同样的方式,找不到True
,所以你得到第二个表达式的False
。
通常,all
和any
不会直接用于列表;将它们与发电机一起使用非常普遍。例如,
any(x in [0, 2] for x in [0, 1]) # "is any of [0, 1] in [0, 2]?"
all(x in [0, 2] for x in [0, 1]) # "is all of [0, 1] in [0, 2]?"
函数qazxsw poi返回boolean qazxsw poi如果可迭代对象中的所有项都是all()
和True
(如果有的话)是True
:
False
返回False
,因为all([0, 1]) # return True if all items are True
被认为是False
,当0
返回False
,因为False 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]
或True
它返回1
。
[0, 2]
在python中,零的真实性,空的False
,In [1]: 1 == True
Out[1]: True
In [2]: 0 == False
Out[2]: True
In [3]: 2 == True
Out[3]: False
被定义为false
list