Python - Lambda 函数用于检查列表中是否存在某个值

pythonserver side programmingprogramming更新于 2024/1/21 22:21:00

Python 中的 Lambda 函数是无名函数,当我们想要在一行中组合多个表达式时,它们非常有用。当我们确定不会在程序中的其他任何地方重复使用代码时,lambda 函数非常方便。但是,如果表达式很长,我们可能希望改用常规函数。在本文中,我们将了解如何使用 lambda 函数检查列表中是否存在某个值。

使用 filter 方法

Python 中的 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 方法以累积方式检查列表中是否存在某个值。


相关文章