Map () and reduce () functions are built in # map/reducefrom functools import reduce# python # map () The function receives two parameters, one is the function, the other is Iterable,map the passed function to each element of the sequence sequentially, and returns the result as a new iterator def f (x): Return x * xr = map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) Print (list (r)) print (R) # map () the first parameter passed in is F, which is the function object itself # because the result R is a iterator,iterator is an inert sequence, so through list ( function allows it to calculate the entire sequence and return a list# map as a higher order function, in fact it abstracts the arithmetic rules, it can calculate any complex function # the list all the numbers into the string l = list (map ( STR, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print (l) # Reduce takes a function in a sequence [x1, x2, x3, ...], this function must receive two parameters # reduce the result continues and the next element of the sequence is calculated # The effect is reduce (f, [x1, x2, x3, x4]) = f (f (f (x1, x2), x3), x4) # uses reduce to sum a sequence of Def add (x, y): return x + ys = reduce (ADD, [1, 3, 5, 7, 9]) print (s) # of course, the sum operation can be directly in Python built function sum (), no need to use reduce# but if you want to put the sequence [1, 2, 5, 7,  9] transform into an integer 13579,reduce can come in handy Def fn (x, y): return x * 10 + ys = reduce (Fn, [1, 3, 5, 7, 9]) print (s) # consider the string str is also a sequence , with map (), we can write the function def fn (x, y) that converts str to int: return x * 10 + ydef char2num (s): return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}[s]s = reduce (Fn, map (char2num, ' 13579 ')) print (s) # Organize into a str2int function def str2int (s): def fn (x, y): return x * 10 + y def char2num (s) : return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}[s] return reduce (Fn, map (char2num, s)) s = str2int (' 112233 ') print (s) # Further simplifies def char2num (s) with the Lambada function: return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}[s]def str2int (s): return reduce (lambda x, y: x * 10 + y, map (char2num, s)) print (Str2Int (' 9999 ')) # The use of lambda functions is not described in detail here
Python---map/reduce