python all() 函數接受一個可迭代對象(如列表、字典等)。如果傳遞的 iterable 中的所有項都為真,則返回 True,否則返回 False。如果可迭代對象為空,則 all() 函數返回 True。
簽名
all (iterable)
參數
- iterable -包含元素的對象,即列表、元組和字典等。
返回
- 真的——如果迭代中的所有元素都為真。
- 錯——如果迭代中的所有元素都是假的..
Python all() 函數示例 1
讓我們看看 all() 是如何處理列表的?
# all values true
k = [1, 3, 4, 5]
print(all(k))
# all values false
k = [0, False]
print(all(k))
# one false value
k = [1, 3, 4, 0]
print(all(k))
# one true value
k = [0, False, 5]
print(all(k))
# empty iterable
k = []
print(all(k))
輸出:
True False False False True
Python all() 函數示例2
下麵的例子展示了 all() 如何為字典工作。
# Both the keys are true
dict1 = {1:'True', 2:'False'}
print(all(dict1))
# One of the key is false
dict2 = {0:'True', 1:'True'}
print(all(dict2))
# Both the keys are false
dict3 = {0:'True', False:0}
print(all(dict3))
# Empty dictionary
dict4 = {}
print(all(dict4))
# Here the key is actually true because
# 0 is non-null string rather than a zero
dict5 = {'0':'True'}
print(all(dict5))
輸出:
True False False True True
Python all() 函數示例3
下麵的例子展示了 all() 如何處理元組。
# all true values
t1 = (1, 2, 3, 4, 5)
print(all(t1))
# one false value
t2 = (0, 1, "Hello")
print(all(t2))
# all false values
t3 = (0, False , 0)
print(all(t3))
# one true value, all false
t4 = (True, 0, False)
print(all(t4))
輸出:
True False False False
相關用法
- Python all()用法及代碼示例
- Python unittest assertNotIsInstance()用法及代碼示例
- Python Tkinter askopenfile()用法及代碼示例
- Python unittest assertIsNotNone()用法及代碼示例
- Python unittest assertFalse()用法及代碼示例
- Python Tkinter asksaveasfile()用法及代碼示例
- Python unittest assertIs()用法及代碼示例
- Python unittest assertNotIn()用法及代碼示例
- Python unittest assertAlmostEqual()用法及代碼示例
- Python ascii()用法及代碼示例
- Python unittest assertGreater()用法及代碼示例
- Python unittest assertIsNot()用法及代碼示例
- Python abs()用法及代碼示例
- Python unittest assertLessEqual()用法及代碼示例
- Python unittest assertEqual()用法及代碼示例
- Python any()用法及代碼示例
- Python unittest assertIsNone()用法及代碼示例
- Python attr.asdict()用法及代碼示例
- Python unittest assertNotAlmostEqual()用法及代碼示例
- Python unittest assertNotEqual()用法及代碼示例
注:本文由純淨天空篩選整理自 Python all() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。