python 函數all()
將 iterable 作為參數,如果迭代中的所有元素都為 TRUE,則返回 True,否則返回 FALSE。
**all(iterable)** #Where iterable can be a list, string, tuple, dictionary , set etc
所有()參數:
all()
只接受一個強制參數。任何 iterable 都可以作為參數傳遞給all()
方法。
參數 | 描述 | 必需/可選 |
---|---|---|
可重復的 | 任何可條目,如列表、元組、字符串、字典等 | 需要 |
全部()返回值
返回一個布爾值,為真或假。只有當可迭代表中的所有元素都為真并且可迭代表為空時,才返回真。在所有其他情況下,該函數返回 False。
| 投入 | 輸出 | | 可迭代真值中的所有值 | 真實的 | | 可迭代 False 中的所有值 | 錯誤的 | | 可迭代真值中除一個元素外的所有元素 | 錯誤的 | | 可迭代 False 中除一個元素外的所有元素 | 錯誤的 | | 空可重復 | 真實的 |
Python 中all()
方法的示例
示例 1:將列表/元組作為參數傳遞
l = [1, 3, 4, 5]
print(all(l))
# all values false l = [0, False] print(all(l))
t = (1,0,1)
print(all(t)) t= ()
print(all(t))
輸出:
True
False False True
示例 2:將字符串作為參數傳遞
s = "This is a non empty string" print(all(s))
s = '000'
print(all(s))
s = ''
print(all(s))
將字符串作為參數傳遞時,最重要的是“0”為真,0 為假
輸出:
True
True
True
示例 3:將字典作為參數傳遞
d = {1: 'False', 2: 'False'} print(all(d))
d = {0: 'True', 2: 'True'} print(all(d))
d = {1: 'True', False: 0} print(all(d))
d = {}
print(all(d))
對于字典,如果所有鍵都為真,則函數返回真,而不考慮值。
輸出:
True
False
False
True