Python Lambda 函数用于检查值是否在列表中

Python Lambda 函数用于检查值是否在列表中

Lambda 函数在 Python 中是无名称的函数,在我们想要在一行中结合多个表达式时很有用。当我们确定这段代码不会在程序的其他地方重复使用时,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库来使用它。

示例

在下面的示例中,我们使用了lambda函数和Python的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方法来以累积的方式检查一个值在列表中的存在。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程