关于all()和any()函数的困惑

问题描述 投票:1回答:4

我正在学习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]
python syntax
4个回答
1
投票

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

2
投票

你误解了你的表达式是如何计算的。首先,请注意0是假的,1是真的。 all([0,1])False,因为并非所有元素都是真实的。 any([0,1])True,因为有些元素是真实的。然后你在False寻找True[0, 2]的会员资格。当作为数字时,True的值为1,而False的值为0。因此,False in [0, 2]评估为True因为False == 0True,所以False[0, 2]“被发现”。以同样的方式,找不到True,所以你得到第二个表达式的False

通常,allany不会直接用于列表;将它们与发电机一起使用非常普遍。例如,

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]?"

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]

0
投票

在python中,零的真实性,空的FalseIn [1]: 1 == True Out[1]: True In [2]: 0 == False Out[2]: True In [3]: 2 == True Out[3]: False 被定义为false

list
© www.soinside.com 2019 - 2024. All rights reserved.