本文概述
Python允许我们不以标准方式声明函数, 即使用def关键字。而是使用lambda关键字声明匿名函数。但是, Lambda函数可以接受任意数量的参数, 但是它们只能以表达式形式返回一个值。
匿名函数包含一小段代码。它模拟C和C ++的内联函数, 但不完全是内联函数。
下面给出了定义匿名函数的语法。
lambda arguments : expression
例子1
x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned.
print("sum = ", x(20))
输出
sum = 30
例子2
Lambda函数的多个参数
x = lambda a, b:a+b # a and b are the arguments and a+b is the expression which gets evaluated and returned.
print("sum = ", x(20, 10))
输出
sum = 30
为什么要使用lambda函数?
当我们在另一个函数中匿名使用lambda函数的主要角色时, 可以在场景中更好地描述它们。在python中, lambda函数可用作自变量, 而高阶函数可用作自变量。在需要考虑以下示例的情况下, 也可以使用Lambda函数。
例子1
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number?"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda function which is called again and again with the iteration variable i
for i in range(1, 11):
print(n, "X", i, "=", b(i)); #the lambda function b is called with the iteration variable i,
输出
Enter the number?10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
例子2
将lambda函数与过滤器一起使用
#program to filter out the list which contains odd numbers
List = {1, 2, 3, 4, 10, 123, 22}
Oddlist = list(filter(lambda x:(x%3 == 0), List)) # the list contains all the items of the list for which the lambda function evaluates to true
print(Oddlist)
输出
[3, 123]
例子3
在地图上使用lambda函数
#program to triple each number of the list using map
List = {1, 2, 3, 4, 10, 123, 22}
new_list = list(map(lambda x:x*3, List)) # this will return the triple of each item of the list and add it to new_list
print(new_list)
输出
[3, 6, 9, 12, 30, 66, 369]
评论前必须登录!
注册