[英]Confusion about all() and any() functions
我正在學習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()
返回bolean True
如果迭代對象的所有項目都是True
和False
,如果任何是False
:
all([0, 1]) # return True if all items are True
返回False
因為0
被認為是False
並且當False in [0, 2]
0 == False
返回True
,因為0 == False
。
對於any([0,1]) in [0,2] #False. Why? 0 is in [0,2]
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
您誤解了表達式的計算方式。 首先,請注意0
是虛假的,而1
是真實的。 all([0,1])
為False
因為並非所有元素都是真實的。 any([0,1])
為True
因為某些元素是真實的。 然后,在[0, 2]
尋找False
和True
的成員資格。 當作為數字時, True
的值為1
, False
的值為0
。 因此, False in [0, 2]
False == 0
評估為True
因為False == 0
為True
,因此在[0, 2]
“發現”了False
。 同樣,找不到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]?"
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
在python中,零,空list
, None
的真實性定義為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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.