Python all() 函式



Python all() 函式是一個內建函式,如果給定可迭代物件(如列表、元組、集合或字典)的所有元素都為真值,則返回True;如果任何值都為假值,則返回False。但是,如果可迭代物件為空,則返回True

可迭代物件是可以透過迭代檢索其元素的物件。在 Python 中,任何非空字串和可迭代物件以及任何非零值都被認為是 True。而空可迭代物件和字串、數字 0 和值 None 被認為是 False。

語法

以下是 Python all() 函式的語法:

all(iterable)

引數

Python all() 函式接受單個引數:

  • iterable − 此引數指示一個可迭代物件,例如列表、元組、字典或集合。

返回值

Python all() 函式返回一個布林值。

示例

下面的示例演示了 all() 函式的工作原理:

示例 1

以下示例顯示了 Python all() 函式的用法。這裡我們建立一個名為“numerics”的列表,並應用 all() 函式來檢查給定列表是否包含真值。

numerics = [71, 87, 44, 34, 15]
output = all(numerics)
print("The output after evaluation:", output)

執行上述程式時,會產生以下結果:

The output after evaluation: True

示例 2

在下面的程式碼中,我們將建立一個水果列表,然後使用 all() 函式檢查它是否包含真值。

fruit_names = ["carrot", "banana", "dragon fruit", "orange"]
output = all(fruit_names)
print("The output after evaluation:", output)

以下是上述程式碼的輸出:

The output after evaluation: True

示例 3

在以下示例中,我們對包含假值的列表使用 all() 函式。由於列表包含一個空字串,該方法將返回 False。

numerics = [71, 87, 44, 34, 15, "", 5]
output = all(numerics)
print("The output after evaluation:", output)

上述程式碼的輸出如下:

The output after evaluation: False

示例 4

在這個示例中,我們對空列表使用 all() 函式。在這種情況下,該方法將返回 True,因為空可迭代物件預設被認為具有所有真值。

empty_numerics = []
output = all(empty_numerics)
print("The output after evaluation:", output)

以下是上述程式碼的輸出:

The output after evaluation: True
python_built_in_functions.htm
廣告