Lambda expressions, usually used in situations where a function is required, but do not want to be bothered to name a function , that is, an anonymous function .
The content of the anonymous function represented by Lambda should be simple, and if complex, simply redefine a function, using lambda is a bit too stubborn.
Lambda is used to define an anonymous function, if you want to bind a name to him, it will appear a little superfluous, usually directly using the lambda function. As shown below:
add = lambda x, y : x+yadd(1,2) # 结果为3
So how do you actually use lambda expressions?
1. Application in functional programming
Python provides many features of functional programming, such as map, reduce, filter, sorted, and so on, which support functions as parameters, and lambda functions can be applied in functional programming. As follows:
# 需求:将列表中的元素按照绝对值大小进行升序排列list1 = [3,5,-4,-1,0,-2,-6]sorted(list1, key=lambda x: abs(x))
Of course, it can also be as follows:
list1 = [3,5< Span class= "p" >,-4,-1 ,0,-2 -6]def get_abs (xreturn abs (x) sorted (list1 ,key=get_abs
But the code in this way doesn't look enough pythonic
2, applied in the closure
def get_y(a,b): return lambda x:ax+by1 = get_y(1,1)y1(1) # 结果为2
Of course, you can also implement closures with regular functions, as follows:
def get_y(a,b): def func(x): return ax+b return funcy1 = get_y(1,1)y1(1) # 结果为2
This is just a bit verbose.
So is the lambda function clearer than the normal function in any case?
Definitely not.
There is a sentence in the Zen of Python: Explicit is better than implicit (clear is better than obscure), which means that it is clearer in which way, do not blindly use lambda expressions.
Python--Lambda expression