Python中的lambda函数
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函数时,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函数与map
#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]