Usage of reduce ()
reduceTo function on a sequence [x1, x2, x3, ...] , the function must receive two parameters, reduce and the result continues and the next element of the sequence is accumulated
The effect is:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
For example, to sum a sequence:
>>> from Functools import reduce>>> def add (x, y): return x + y>>> reduce (add, [1, 3, 5, 7, 9]) 25
#这里reduce就是先把1, 3 incoming add calculation, and then calculate the result and 5 again as the parameter of add, go down
Of course, the sum operation can be directly built into Python functions sum() , no need to use reduce .
But if you want to [1, 3, 5, 7, 9] transform the sequence into integers 13579 , you can put reduce it in handy:
>>> from functools import reduce>>> def fn (x, y): return x * + y>>> reduce (FN, [1, 3, 5, 7, 9]) 13579
This example is not very useful in itself, but if we consider that the string str is also a sequence, with a slight change to the above example, map() we can write the str converted int function:
>>> from functools import reduce>>> def fn (x, y): return x * + y>>> def char2num (s):
return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s] >>> reduce (FN, MA P (char2num, ' 13579 ')) 13579
str2intthe function that is organized into one is:
From Functools import reducedef str2int (s): def fn (x, y): return x * + 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))
You can also use lambda functions to further simplify:
From Functools import reducedef char2num (s): return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 8 ': 8, ' 9 ': 9}[s]def str2int (s): return reduce (lambda x, y:x * + y, map (Char2num, s))
That is, assuming that Python does not provide a int() function, you can write a function that converts the string to an integer by itself, and only requires a few lines of code!
Note: The tutorials above are from Liaoche Python3 tutorials: Map () and reduce ()
Reduce ()