Map () and reduce () in Python
Python has the map () and reduce () functions built into it.
Map ()
The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
For example, there is a function f (x) =x^2, in order to function on a list[1,2,3,4,5,6,7,8,9], you can use map () to achieve:
def f (x): return x*x for in range (1,10)] [1, 4, 9, 16, 25, 36, 49, 64, 81]
Map () The first parameter passed in is F, which is the function object itself.
Map () is a high-order function, in fact it abstracts the arithmetic rules, so you can compute any complex function, such as converting all the numbers of a list to a string:
>>> Map (str,[x forXinchRange (1,10)])['1','2','3','4','5','6','7','8','9']
Reduce ()
Reduce puts a function in a sequence [x1,x2,x3, .....] , the function must accept two parameters, and reduce will accumulate the result and the next element of the sequence, the effect is:
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)
For example, to sum a sequence, it can be implemented with reduce:
def Add (x, y ): return x+y for in range (1,101)])
Of course, the sum operation can be built directly into the Python function sum (), no need to use reduce.
But if you convert the sequence [1,3,5,7,9] into an integer 13579,reduce it will come in handy:
def f (x, y ): return x*10+yforif x%2!=0])13579
This example is not very useful in itself, but if you consider that the string str is also a sequence, make a slight change to the above example, with map (), which is the function that can convert str to int:
>>>deffn (x, y):returnX*10 +y>>>defChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]>>> Reduce (Fn,map (Char2num,'13579'))13579
The functions that are organized into a str2int are:
>>>defStr2Int (s):deffn (x, y):returnX*10 +y>>>defStr2Int (s):deffn (x, y):returnX*10 +ydefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]returnReduce (Fn,map (char2num,s))>>> Str2Int ('1234567')1234567
You can also use lambda functions to further simplify:
>>>defChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}[s]>>>defStr2Int (s):returnReduceLambdax,y:x*10+y, Map (char2num,s))>>> Str2Int ('13579')13579
Python Advanced Tutorial-map/reduce