1 syntax
Lambda arg1, arg2:arg1 + arg2 + 1
Arg1, arg2: Parameters
Arg1 + arg2 + 1: expression
2 description
The anonymous function does not need a return value, and the expression itself results in a return value.
Lambda is simply code-less and does not improve program performance
If you can use for ... in ... if To complete, it is best not to use the anonymous function lambda
When using lambda, the function does not include loops, nesting, or, if it does exist, it is best to use the DEF function, which makes the code more readable and reusable
Lambda is used to write simple functions, and DEF is used to handle more powerful tasks.
3 Example 3.1 anonymous function with no parameters
Lambda:5>>> a<function <lambda> at 0x7f20f53be2f0>>>> A ()
3.2 Anonymous functions for single parameters
Lambda x:x+1print(A (2))
Run: 3
3.3 Anonymous functions with multiple parameters
Lambda x, y:x + y + 1print(A ())print(A (y=3,x=2))
Run:
46
3.4 Other
1 Lambda x:x+1 (1)2 <function <lambda> at 0x7f20f4cfb9d8>
Some blogs say that the first line of input can directly get the result, in fact, only get the address of the anonymous function (hex)
Lambda x:x+1 (1)<function <lambda> at 0x7f20f4cfb9d8>>>> ID ( Lambda x:x+1 (1))139779554729768>>> hex (ID (lambda x:x+1 (1)))' 0x7f20f4cfb9d8'
If the function value needs to be obtained, the
>>> (Lambda x:x+1) (1)2
Same
Print (Lambda x:x+1 (1)) # <function <lambda> at 0x7fa097b54f28> Print (Lambda x:x+1) (1)) # 2
Calculation
( lambda x: ( Lambda y: (lambda z:x + y + z) (1)) (2)) (3)
equals how much? 6
Refer to Python's anonymous function lambda interpretation and usage, Python learning Note (12): lambda expression and functional programming, Python lambda introduction
Python Learning note 010--anonymous function lambda