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