官方文档: #functools.reduce
源代码: Lib/functools.py
# 定义
import functools
functools.reduce(function, sequence[, initial]) -> value
官方解释:
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.
意思就是,对一个 sequence 迭代地使用 function,将传入的 sequence reduce 到一个 value 的过程。
若给出了初始值 initial,则第一次调用 function 时传递的参数为 initial 和 sequence 的第一个元素,否则传递的参数为 sequence 的前两个元素,从第二次迭代开始每次传入前一次的计算结果和 sequence 的下一个元素。
比如上面官方给出的例子:
import functools
functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
>>>
15
function 为 x + y,sequence 为 [1, 2, 3, 4, 5],未给出 initial,所以:
第一次计算 (1 + 2)
第二次计算 ((1 + 2) + 3)
…
整个过程就是:((((1+2)+3)+4)+5) = 15。
给出了 initial 的例子:
import functools
a = functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 20)
>>>
35
初始值为 20,所以计算过程为 (((((20+1)+2)+3)+4)+5) = 35。