python anonymous function lambda usage

Before introducing anonymous functions, let's take a look at these two functions:

def add(x,y):
    return x+y
print(add(1,2))   #3
f=lambda x,y:x+y
print(f(1,2))

The functions of the above two pieces of code are exactly the same. Inside the second piece of code: lambda x,y:x+y This is a function. Since there is no function name, it is called an anonymous function.

Let's take a closer look at anonymous functions:

1. Anonymous function: no function name. declared with a lambda.
2. Format of anonymous function:
      lambda arg1,arg2,.....argn:expression
   The colon is the delimiter, before the colon is the parameter of the function, and after the colon is an expression.
3. Anonymous functions do not need to use return. The following expression is the return value 
4. Call method: assign an anonymous function to a variable, and then the variable can be used like a normal function

 

#No parameters: 
f= lambda : ' abc ' 
print (f())     # 'abc'

# 
f= lambda with multiple arguments a,b,c: a+b+ c
 print (f(1,2,3))    # 6

# with default parameters 
f= lambda a,b,c=4: a+b+ c
 print (f(1,2))     # 7

 

Advanced usage skills of anonymous functions: combined with map.reduce, filter use:

from functools import  reduce
data=[1,2,3,4,5,6,7,8,9,10]
print(reduce(lambda x,y:x+y,data))   #55

  

data=[1,2,3,4,5,6,7,8,9,10 ]
 print (list(map( lambda x:x* x,data)))  
 #The output is [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325126574&siteId=291194637