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

时间:2019-02-20 11:33:49

标签: python syntax

我正在学习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]

4 个答案:

答案 0 :(得分:2)

如果可迭代对象中的所有项目均为all(),则函数True返回布尔值True,如果FalseFalse,则返回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]False,并返回In [1]: 1 == True Out[1]: True In [2]: 0 == False Out[2]: True In [3]: 2 == True Out[3]: False

$isFirstNotInstalledCases = $em->getRepository(User::class)
        ->createQueryBuilder('u')
        ->select("u.phone as phone")
        ->addSelect("u.isFirstInstalled as isFirstInstalled")
        ->where("u.phone IN (:phone)")
        ->andWhere("u.isFirstInstalled = :isFirstInstalled")
        ->setParameters(['isFirstInstalled'=>0,'phone'=>$phones])
        ->getQuery()
        ->getArrayResult();

答案 1 :(得分: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 :(得分: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

答案 3 :(得分:0)

在python中,零的真实性,空listNone被定义为false

    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([None,1]) in [None,2]    #False.
    any([[],1]) in [[],2]    #False.