Lambda is just an expression, and the function body is much simpler than def. The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression. A lambda expression acts as a function sketch. Allows the definition of a function to be embedded within the code.
#求三个数的和
1Lambda x,y,z:x+y+x2print(f ()) #43 4 Lambda x,y,z:x+y+z5print(f (6)) #
In a normal def function construct, there can be any number of statements, and in the DEF function definition, the first need to give the function a name, for the lambda expression, lambda is an anonymous function, do not need to give a lambda construct any name.
The lambda construct is more convenient, and when you need to construct a lambda function, keep in mind the following points:
1, Lambda is an expression, not a statement, it does not support expression blocks.
2. Lambda is defined where we need it, and it doesn't need to be named.
3. Lambda does not need a return statement
The construction of a lambda with a single parameter
1 # lambda structure construction with a single parameter 2 x = [23,34,55]3Lambda x:max (x)4print(func (x)) #
Lambda constructs with multiple parameters:
1 # Lambda constructs with multiple parameters 2 price,volume = 60,203Lambda price,volume:price/volume4Print (func (price,volume)) #3.0
Lambda constructs with logical operators
1 # Lambda constructs with logical operators 2 ' SELL ' 3 Lambda and ' BUY ' 4 Print (func ()) # False
Lambda constructs with conditional expressions
1 # Lambda constructs with conditional expressions 2 Lambda x:'BUY'ifelse'SELL' 3print(func) #BUY
Building a lambda expression with multiple if...else statements
1 # lambda expression with multiple conditional statements 2 Lambda x:'BUY'ifelse'SELL' ifelse'None'3print(func (78) ) #SELL
Use a lambda expression with the map, filter, and reduce features
Lambda is typically used in conjunction with functions such as map (), filter (), and reduce ()
1 # Lambda is used with map () mapping functions 2 seq = [1,2,3,4,5]3 func = map (Lambda x:x**2, seq)4Print (List (func)) #[1, 4, 9, +]
1 #Lambda is used with the filter () filter function2Signals = ['Buy','Sell', None,'Sell','Sell','Sell']3Func = Filter (LambdaX:x = ='Buy' orx = ='Sell', signals)4 Print(List (func))#[' Buy ', ' Sell ', ' Sell ', ' Sell ', ' Sell ']
1 # Lambda is used with the reduce () function 2 # In Python 3, the reduce () function has been removed from the global namespace and is now placed in the Fucntools module 3 # If you want to use it, you need to call the reduce () function by introducing the Functools module: 4 from Import Reduce 5 Print (Reduce ((lambda x,y:x + y), [2,1.35,-2.4,3])) # 3.95
Reference:
1, https://www.quantinsti.com/blog/popular-python-learning-the-lambda-function/
2, 8667176
Python Learning-lambda expressions