Python Lambda函数

Python Lambda函数是匿名函数,意味着该函数没有名称。我们已经知道 def 关键字用于定义Python中的普通函数。同样地 拉姆达 关键字用于定义Python中的匿名函数。

null

Python Lambda函数语法:

lambda arguments: expression
  • 此函数可以有任意数量的参数,但只能有一个表达式,该表达式将被计算并返回。
  • 一种是在需要函数对象的地方自由使用lambda函数。
  • 您需要了解lambda函数在语法上仅限于一个表达式。
  • 除了函数中的其他类型的表达式之外,它在特定的编程领域中有各种用途。

示例:Lambda函数示例

Python3

# Python program to demonstrate
# lambda functions
string = 'GeeksforGeeks'
# lambda returns a function object
print ( lambda string : string)


输出

<function <lambda> at 0x7f65e6bbce18>

在上面的示例中,打印函数不会调用lambda,而只是返回函数对象和存储它的内存位置。

所以,为了打印字符串,我们首先需要调用lambda,这样字符串就可以通过打印。

例子:

Python3

# Python program to demonstrate
# lambda functions
x = "GeeksforGeeks"
# lambda gets pass to print
( lambda x : print (x))(x)


输出

GeeksforGeeks

Lambda函数和def定义函数之间的差异

让我们看看这个例子,试着理解普通def定义函数和lambda函数之间的区别。这是一个返回给定值的立方体的程序:

python

# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y * y * y
lambda_cube = lambda y: y * y * y
# using the normally
# defined function
print (cube( 5 ))
# using the lambda function
print (lambda_cube( 5 ))


输出:

125125

正如我们在上面的例子中所看到的,cube()函数和lambda_cube()函数的行为都是一样的。让我们进一步分析一下上面的例子:

  • 不使用Lambda: 在这里,它们都返回给定数字的立方体。但是,在使用def时,我们需要定义一个名为cube的函数,并需要向其传递一个值。执行之后,我们还需要返回使用 回来 关键词。
  • 使用Lambda: Lambda定义不包含“return”语句,它始终包含返回的表达式。我们也可以将lambda定义放在任何需要函数的地方,而且根本不需要将它赋给变量。这就是lambda函数的简单性。

让我们来看一些更常用的lambda函数示例。

示例1:具有列表理解功能的Python Lambda函数

在本例中,我们将使用lambda函数进行列表理解,使用lambda函数进行for循环。我们将尝试打印10人的表格。

Python3

tables = [ lambda x = x: x * 10 for x in range ( 1 , 11 )]
for table in tables:
print (table())


输出

102030405060708090100

示例2:带有if-else的Python Lambda函数

Python3

# Example of lambda function using if-else
Max = lambda a, b : a if (a > b) else b
print ( Max ( 1 , 2 ))


输出

2

示例3:带有多条语句的Python Lambda

Lambda函数不允许多个语句,但是,我们可以创建两个Lambda函数,然后调用另一个Lambda函数作为第一个函数的参数。让我们尝试使用lambda找到第二个最大元素。

Python3

List = [[ 2 , 3 , 4 ],[ 1 , 4 , 16 , 64 ],[ 3 , 6 , 9 , 12 ]]
# Sort each sublist
sortList = lambda x: ( sorted (i) for i in x)
# Get the second largest element
secondLargest = lambda x, f : [y[ len (y) - 2 ] for y in f(x)]
res = secondLargest( List , sortList)
print (res)


输出

[3, 16, 9]

在上面的示例中,我们创建了一个lambda函数,用于对给定列表的每个子列表进行排序。然后,该列表作为参数传递给第二个lambda函数,该函数返回排序列表中的n-2元素,其中n是子列表的长度。

Lambda函数可以与内置函数一起使用,如 过滤器() , 地图() 减少 .

将lambda()函数与filter()一起使用

Python中的filter()函数接受函数和列表作为参数。这提供了一种优雅的方法,可以过滤掉序列“sequence”中的所有元素,函数将为其返回True。下面是一个从输入列表中返回奇数的小程序:

例1:

python

# Python code to illustrate
# filter() with lambda()
li = [ 5 , 7 , 22 , 97 , 54 , 62 , 77 , 23 , 73 , 61 ]
final_list = list ( filter ( lambda x: (x % 2 ! = 0 ) , li))
print (final_list)


输出:

[5, 7, 97, 77, 23, 73, 61]

例2:

Python3

# Python 3 code to people above 18 yrs
ages = [ 13 , 90 , 17 , 59 , 21 , 60 , 5 ]
adults = list ( filter ( lambda age: age> 18 , ages))
print (adults)


输出:

[90, 59, 21, 60]

将lambda()函数与map()一起使用

Python中的map()函数接受函数和列表作为参数。使用lambda函数和列表调用该函数,并返回一个新列表,其中包含该函数为每个项返回的所有lambda修改项。例子:

例1:

python

# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [ 5 , 7 , 22 , 97 , 54 , 62 , 77 , 23 , 73 , 61 ]
final_list = list ( map ( lambda x: x * 2 , li))
print (final_list)


输出:

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

例2:

Python3

# Python program to demonstrate
# use of lambda() function
# with map() function
animals = [ 'dog' , 'cat' , 'parrot' , 'rabbit' ]
# here we intend to change all animal names
# to upper case and return the same
uppered_animals = list ( map ( lambda animal: str .upper(animal), animals))
print (uppered_animals)


输出:

['DOG', 'CAT', 'PARROT', 'RABBIT']

将lambda()函数与reduce()一起使用

Python中的reduce()函数接受函数和列表作为参数。使用lambda函数和iterable调用该函数,并返回一个新的简化结果。这会对iterable的对执行重复操作。reduce()函数属于 功能工具 单元

例1:

python

# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [ 5 , 8 , 10 , 20 , 50 , 100 ]
sum = reduce (( lambda x, y: x + y), li)
print ( sum )


输出:

193

在这里,前两个元素的结果被添加到下一个元素中,这一直持续到列表的末尾,比如((((((((5+8)+10)+20)+50)+100)。

例2:

Python3

# python code to demonstrate working of reduce()
# with a lambda function
# importing functools for reduce()
import functools
# initializing list
lis = [ 1 , 3 , 5 , 6 , 2 , ]
# using reduce to compute maximum element from list
print ( "The maximum element of the list is : " ,end = "")
print (functools. reduce ( lambda a,b : a if a > b else b,lis))


输出:

The maximum element of the list is : 6

本文由 金莫伦卡 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享