Python Note 4 (Anonymous Functions)

1. Introduction to anonymous functions

Anonymous function: a one-sentence function designed to solve the needs of those functions that are very simple

Function name = lambda parameter:
There can be multiple return value parameters. Separate anonymous functions with commas.
No matter how complicated the logic is, only one line can be written, and the content after the logic execution is the return value. The
return value can be arbitrary like a normal function. type of data

2. lambda expressions

1  # lambda expression 
2  def add(a,b):
 3      return a+ b
 4  
5 add = lambda a,b : a+ b
 6  print (add(1,2 ))
 7  
8  # 1. Return the square of 1~10 
9 [i**2 for i in range(10 )]
 10  def func(num):
 11      return num ** 2
 12  
13  for i in map(func,range(10)): print (i)
 14  
15  #Use lambda expression 
16  for i in map( lambda num : num ** 2 ,range(10)): print (i)
 17  
18  # 2. Calculate the minimum value of elements 
19  def func(num):
 20      return num%2
 21  print (min(-2,3,-4,key= func))
 22  #Use lambda expression 
23  print (min(-2,3,-4,key= lambda num:num%2 ))
 24  
25  # 3. What is the output of the code 
26 d = lambda p:p*2
 27 t = lambda p:p*3
 28x = 2
 29 x = d(x)    # x = 4 
30 x = t(x)    # x = 12 
31 x = d(x)
 32  print (x)
 33  # >>>24 
34  
35  # 4. Existing Two tuples (('a'), ('b')), (('c'), ('d')), please use an anonymous function in python to generate a list [{'a':'c'}, {'b':'d'}] 
​​36  def func(t):
 37      return {t[0]:t[1 ]}
 38  
39 ret = map(func,zip((( ' a ' ),( ' b ' )),(( ' c ' ),('d'))))
 40  print (list(ret))
 41  #Use lambda expression 
42 ret = map( lambda t:{t[0]:t[1]},zip((( ' a ' ),( ' b ' )),(( ' c ' ),( ' d ' ))))
 43  print (list(ret))
 44  
45  # 5. What is the output of the following code? Please give an answer and explain. 
46  def multipliers():
 47      return [ lambda x:i*x for i in range(4 )]
 48  print([m(2) for m in multipliers()])
49 #>>>[6, 6, 6, 6]
50 
51 #分析
52 # def multipliers():
53 #     lst = []
54 #     i = 0
55 #     lst.append(lambda x:i*x)
56 #     i = 1
57 #     lst.append(lambda x:i*x)
58 #     i = 2
59 #     lst.append(lambda x:i*x)
60 #     i = 3
61 #     lst.append(lambda x:i*x)
62 #     # lst = [lambda x:3*2,lambda x:i*x,lambda x:i*x,lambda x:i*x] 
63  #      return lst 
64  # print([m(2) for m in multipliers( )]) 
65  
66  # 6. Please modify the definition of multipliers to produce the desired result 
67  # def multipliers(): 
68  #      return [lambda x:i*x for i in range(4)] 
69 g = ( lambda x: i*x for i in range(4)) #List comprehension modified into generator expression 
70  print ([m(2) for m in g])

 

Guess you like

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