Python中的 lamda表达式
lambda
statements are used to create new function objects, and they are returned at run time.
python Lambda is the use of lambda in Python to create anonymous functions, and the method created with Def is named, except for the name of the method on the surface, Python lambda is not the same as the def?
1 python Lambda will
2 python Lambda It's just an expression, and DEF is a statement.
A lambda expression can have only one expression after ":". That is, in Def, return can also be placed behind a lambda, and cannot be returned with return can not be defined behind a Python lambda. Therefore, a statement such as if or for or print cannot be used in a lambda, and lambda is generally used only to define simple functions.
Use LAMDA form
<span style= "FONT-SIZE:18PX;" >def make_repeater (n): return lambda s:s*ntwice = Make_repeater (2) print (twice (' word ')) print (twice (5)) </ Span>
How it works:
Here, we used the make_repeater
function creates a new function object at run time and returns it. lambda
statement is used to create a function object. Essentially, lambda
requires a parameter (possibly multiple parameters), followed by only a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even print
Statement also cannot be used in lambda form, only expressions are used.
Let's look at more examples:
1 for single parameters:
g = Lambda x:x*2print (g (3))
The result is 6, the analysis (x is the formal parameter of the function, x*2 is the function body)
More than 2 parameters:
m = lambda x, y, Z: (x-y) *zprint (M (3,1,2)) (x, Y, Z is the function's formal parameter, (x-y) *z is the function body)
The result is 4 .
Lamda Expressions in Python