Anonymous Functions
- A lambda function is a minimal function that quickly defines a single line, and can be used wherever a function is needed
As an example:
>>> def f(x,y):... return x*y...>>> f(2,3)6>>> g = lambda x,y:x*y>>> g(2,3)6>>> g<function0x103e12c08>
- When using Python to write some execution scripts, using lambda eliminates the process of defining a function, making the code more streamlined.
- For some abstract functions that are not reused elsewhere, sometimes it is difficult to name a function, and using lambda does not have to consider naming problems.
- Using lambda makes your code easier to understand at some point.
- In a lambda statement, the colon is preceded by a parameter, which can have multiple, comma-separated. After the colon is the return value. A lambda statement is actually built as a function object.
Recursive
5*4*3*2*1120>>> def f(n):... if0:... return n*f(n-1)... if0:... return1...>>> f(5)120
- But recursion is not so well understood, so we're leading to reduce
Reduce
You need to define a function to help reduce
>>> l = range(1,6)>>> l[12345]>>> def f(x,y):... return x*y...>>> reduce(f,l)120
Here we find that the function of defining f is not necessary and can be converted into lambda instead.
>>> reduce(lambda x,y:x*y, l)120
This avoids meaningless function definitions.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python Lambda expression