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

📅  最后修改于: 2022-05-13 01:55:17.895000             🧑  作者: Mango

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

给定一个列表,任务是编写一个Python程序来使用 lambda函数检查该值是否存在于列表中。

例子:

Input  :  L = [1, 2, 3, 4, 5]
          element = 4
Output :  Element is Present in the list

Input  :  L = [1, 2, 3, 4, 5]
          element = 8
Output :  Element is NOT Present in the list

我们可以使用以下两种方法来实现上述功能。

方法一:使用 Lambda 和 Count() 方法

用整数定义一个列表。定义一个 lambda函数,使其将数组和值作为参数并返回列表中值的计数。

如果计数为零,则打印元素不存在,否则打印元素不存在。

Python3
arr = [1, 2, 3, 4]
v = 3
  
def x(arr, v): return arr.count(v)
  
  
if(x(arr, v)):
    print("Element is Present in the list")
else:
    print("Element is Not Present in the list")


Python3
arr=[1,2,3,4]
v=8
x=lambda arr,v: True if v in arr else False
  
if(x(arr,v)):
  print("Element is Present in the list")
else:
  print("Element is Not Present in the list")


输出:

Element is Present in the list

解释: arr 和 v 被传递给 lambda函数,它计算 arr 中 v 的计数,这里 v = 3,它在数组中出现 1 次,并且满足 if 条件并打印元素 Is present in the列表。

方法二:使用 Lambda 和 in 关键字

用整数定义一个列表。定义一个 lambda函数,使其将数组和值作为参数,并使用 in 关键字检查值是否存在于数组中

如果 lambda 返回 True 则打印元素存在,否则打印元素不存在。

Python3

arr=[1,2,3,4]
v=8
x=lambda arr,v: True if v in arr else False
  
if(x(arr,v)):
  print("Element is Present in the list")
else:
  print("Element is Not Present in the list")

输出:

Element is Not Present in the list

解释: arr 和 v 被传递给 lambda函数,它使用 IN 关键字检查值是否存在于数组中,这里 v = 8 并且它不存在于数组中并返回 false 所以打印元素不存在于名单。