Python functools. reduce usage, functools. reduce
After python 3.0, reduce is no longer in the built-in function. to use it, you need to import reduce from functools.
Reduce usage
Reduce (function, sequence [, initial])-> value
Apply a function of two arguments cumulatively to the items of a sequence,
From left to right, so as to reduce the sequence to a single value.
For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]) calculates
(1 + 2) + 3) + 4) + 5). If initial is present, it is placed before the items
Of the sequence in the calculation, and serves as a default when
Sequence is empty.
This means that the function is used continuously for sequence. If initial is not given, two elements of sequence will be transferred for the first call, and the result of the previous call and the next element of sequence will be passed to the function. if initial is given, the first element of initial and sequence is passed to the function for the first time.
From functools import reduce (lambda x, y: x + y, [1, 2, 3]) Outputs 6 reduce (lambda x, y: x + y, [1, 2, 3], 9) Output 15 reduce (lambda x, y: x + y, [1, 2, 3], 7) Output 13
* The standard functool Library also provides many functions. For more information, see the online documentation.