Python – 使用Lambda函式檢查值是否在列表中
Python 中的 lambda 函式是匿名函式,當我們想要在一行中組合多個表示式時非常有用。當我們確定不會在程式的其他任何地方重用程式碼時,lambda 函式很方便。但是,如果表示式很長,我們可能需要改用常規函式。在本文中,我們將瞭解如何使用 lambda 函式檢查值是否存在於列表中。
使用 filter 方法
Python 中的 filter 方法是一個內建函式,它根據某些過濾條件建立列表中的新元素。它返回一個 filter 物件,該物件具有布林掩碼,用於指示索引處的元素是否滿足某些條件。我們需要使用 Python 的“list”方法將其轉換回列表資料型別。
示例
在下面的示例中,我們使用了 lambda 函式來處理列表“numbers”的所有元素。使用 filter 方法,我們過濾出了滿足條件的所有元素。接下來,使用“list”方法,我們將過濾後的物件轉換為列表。
def does_exists(numbers, value):
result = list(filter(lambda x: x == value, numbers))
if result:
print("Value found in the list.")
else:
print("Value not found in the list.")
numbers = [1, 2, 3, 4, 5]
value = 3
does_exists(numbers,value)
value=45
does_exists(numbers,value)
輸出
Value found in the list. Value not found in the list.
使用 ‘any’ 和 ‘map’ 方法
‘any’ 是 Python 中的內建方法。如果可迭代物件中的至少一個元素滿足特定條件,則返回 True。如果所有元素都不滿足條件,或者可迭代物件為空,則返回 False。
另一方面,map 方法是 Python 中的內建方法,它允許我們將任何特定函式應用於可迭代物件的所有元素。它將函式和可迭代物件作為引數。
示例
在下面的示例中,我們使用了 'any'、'map' 和 'lambda' 函式來檢查值是否存在於列表中。我們使用 map 方法將 lambda 函式應用於列表的所有元素。接下來,'any' 方法檢查是否至少有一個元素滿足條件。
def does_exists(numbers, value):
result = any(map(lambda x: x == value, numbers))
if result:
print("Value found in the list.")
else:
print("Value not found in the list.")
numbers = [1, 2, 3, 4, 5]
value = 3
does_exists(numbers,value)
value=45
does_exists(numbers,value)
輸出
Value found in the list. Value not found in the list.
使用 ‘reduce’ 方法
Python 中的 reduce 方法允許使用者使用某些特定函式對任何可迭代物件執行一些累積計算。但是,這不是 Python 中的內建方法,我們需要匯入 functool 庫才能使用它。
示例
在下面的示例中,我們使用了 Python 的 lambda 和 reduce 方法。使用 lambda 函式,我們檢查變數 'acc' 或 'x' 的值是否對列表的所有元素都等於所需值。如果在任何迭代過程中任何元素返回 True,則 reduce 方法會立即返回 True 並中斷迭代。
from functools import reduce
def does_exists(numbers, value):
result = reduce(lambda acc, x: acc or x == value, numbers, False)
if result:
print("Value found in the list.")
else:
print("Value not found in the list.")
numbers = [1, 2, 37, 4, 5]
value = 378
does_exists(numbers,value)
value=37
does_exists(numbers,value)
輸出
Value not found in the list. Value found in the list.
計數以檢查是否存在
很容易理解,如果任何元素存在於列表中,則它在列表中的總出現次數必須是非零數。因此,我們只需要計算元素在列表中出現的次數。如果它出現非零次,則它一定存在於列表中。雖然我們可以使用迴圈語句(如 while 迴圈、for 迴圈等),但我們也可以使用名為“count”的內建方法,該方法返回元素在列表中的出現次數。
示例
在下面的示例中,我們對列表使用了“count”方法。我們將所需值作為引數傳遞給該方法。該方法返回元素在列表中的頻率。接下來,我們根據該值在列表中是否出現非零次來列印我們的語句。
def does_exists(numbers, value):
result = numbers.count(value)
if result:
print("Value found in the list.")
else:
print("Value not found in the list.")
numbers = [1, 26, 37, 4, 5]
value = 26
does_exists(numbers,value)
value=378
does_exists(numbers,value)
輸出
Value found in the list. Value not found in the list.
結論
在本文中,我們瞭解瞭如何使用 lambda 函式來檢查值是否存在於列表中。我們使用了 map、filter 等其他幾種方法以及 lambda 函式來實現這一點。此外,我們還學習瞭如何使用 reduce 方法以累積的方式檢查值是否存在於列表中。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP