One, lambda expression
1>>>defAdd (x, y):#Define an addition function2 returnX+y#returns the added value of two parameters3 4>>> z=f (3,4) 5>>>Print(z)67#Call the addition function to return 77>>>Lambdax,y:x+y8<function <Lambda> at 0x0000020f385b86a8>9 #you can see that the lambda is a function class objectTen>>> f=LambdaX,y:x+y#function implementation is the same as add (x, y) One>>> F () A3 ->>> F (3,4) -7 the>>>defmultiply (x, y): - returnx*y - ->>> Multiply (3,4) +12 ->>> multiply=Lambdax,y:x*y +>>> Multiply (3,4) A12 at>>>defsubtract (x, y): - returnX-y - ->>> Subtract (3,4) --1 ->>> subtract=Lambdax,y:x-y in>>> Subtract (3,4) --1 to +>>>defdivide (x, y): - returnx/y the *>>> Divide (4,2) $2.0Panax Notoginseng>>> divide=Lambdax,y:x/y ->>> Divide (4,2) the2.0 + A #the above multiplication function, subtraction function, and division function can all be replaced by lambda expressions, which is more convenient
As you can see from the above, lambda expressions can be conveniently used instead of simple functions.
Two or three-dollar operation
1, see what is ternary operation
2, Python's ternary operation format is as follows:
result= value 1 if x<y else value 2 What does this mean, is the result = value 1 if condition 1 else value 2
1>>>deff (x, y):2 returnX-yifX>yElseABS (xy)3 #if x is greater than Y, it returns an X-y value, otherwise it returns the absolute values of X- y4 5>>> F (3,4)#3<4, does not satisfy the IF condition, it returns the absolute value inside the else6>>> F (4,3)7>>>deff (x, y):8 return1ifX>yElse-19 #if x is greater than Y, it returns an X-y value, otherwise it will return 1.Ten>>> F (3,4)#3 is less than 4, returns-1 One-1 A>>> F (4,3)#4 is greater than 3, returns 1 ->>>
Python-based-LAMBDA expressions and ternary operations