There are some built-in higher-order functions in python, such as
reduce(); they are called higher-order functions because one of the parameters accepted by such functions is a function object.
map() function syntax:
The first parameter received by the map function is a function object, followed by one or more sequences; the map function will apply func to each value in the following sequence and return an iterator.
def func(a): return a**2 >>>map(func,[1,2,3]) <map object at 0x000002B127AEA700>#Return a map object, which is an iterator; >>>list(map(func1,[1,2,3])) [1, 4, 9] #Pass 1,2,3 as parameters into func one by one, get 1,4,9 respectively; finally convert the result to list
You can also pass in multiple sequences, one sequence corresponds to the parameter of a function; the sequence length can be inconsistent, the default is to take the sequence value of the common length;
def func(a,b): return a+b >>>b=list(map(func,[10,20,30],[1,3,10]))#The values of the corresponding positions of the two sequences are applied to func as a and b respectively; >>>print(b) [11, 23, 40]# >>>list(map(func,[10,20,30,40],[1,3,10]))#The length is inconsistent, and a sequence of the same length is taken by default [11, 23, 40] >>>list(map(func,[1,2,3],[10,20,30,40],[1,3,10]))#The number of sequences must be the same as the number of parameters of func TypeError: func() takes 2 positional arguments but 3 were given >>>b=list(map(func,[1,2,3])) TypeError: func() missing 1 required positional argument:'b'
As you can see, the function implemented by the map() function is very similar to the for loop and the list comprehension, so what is the efficiency of the map, for loop and the list comprehension?
import time start=time.time() def func(a,b): return a+b c=list(map(func,range(1000000),range(1000000))) end=time.time() >>>end-start 0.16860485076904297
import time start=time.time() c=list() for i in range(1000000): c.append(i+i) end=time.time() >>>end-start 0.2443540096282959
import time a=list(range(1000000)) b=list(range(1000000)) start=time.time() c=[a[i]+b[i] for i in range(1000000)] end=time.time() print(end-start) 0.2124321460723877
From the above comparison, we can see that map has the highest efficiency and for loop has the lowest efficiency;
Based on this type of function and efficiency of map, when the project involves more loops, you can consider whether you can replace the for loop with Map. On the one hand, the code is more brief and pythonic, and on the other hand, the time efficiency of the code will be higher.