Python any() 函式



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

可迭代物件是一個允許我們透過迭代訪問其元素的物件。在 Python 中,真值包括非空字串、非零數字和非空可迭代物件。另一方面,假值包括空可迭代物件和字串、數字 0 和特殊值 None。

語法

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

any(iterable)

引數

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

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

返回值

Python any() 函式返回布林值。

示例

讓我們透過一些示例瞭解 any() 函式的工作原理:

示例 1

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

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

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

The output after evaluation: True

示例 2

在下面的程式碼中,我們有一個包含四個元素的元組,any() 函式檢查元組的任何元素是否為真值。由於所有四個元素都是假值,此函式將返回 False。

falsy_tup = (False, None, "", 0.0)
output = any(falsy_tup)
print("The output after evaluation:", output)

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

The output after evaluation: False

示例 3

下面的程式碼展示瞭如何使用 any() 函式驗證兩個給定集合之間是否存在任何公共元素。

set1 = {11, 33, 34}
set2 = {44, 15, 26}
output = any(x in set2 for x in set1)
print("Both sets have common elements:", output) 

set1 = {11, 21, 31}
set2 = {31, 41, 51}
output = any(x in set2 for x in set1)
print("Both sets have common elements:", output)

上述程式碼的輸出如下:

Both sets have common elements: False
Both sets have common elements: True

示例 4

在下面的程式碼中,我們使用 `any()` 函式來檢查給定列表中是否存在任何大於零的數字。

numeric_lst = [-15, -22, -54, -41, -11]
output = any(i > 0 for i in numeric_lst)
print("The list contains truthy value:", output) 

numeric_lst = [-15, -42, -23, -41, 11]
output = any(i > 0 for i in numeric_lst)
print("The list contains truthy value:", output)  

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

The list contains truthy value: False
The list contains truthy value: True
python_built_in_functions.htm
廣告