Python reduce()

有了map(),怎么能少了reduce()呢,虽然跟google的MapReduce扯不上关系,但是这名字还是很高大上的,跟map一样,参观下官方文档:

reduce(function, iterable[, initializer])

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. Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        try:
            initializer = next(it)
        except StopIteration:
            raise TypeError('reduce() of empty sequence with no initial value')
    accum_value = initializer
    for x in it:
        accum_value = function(accum_value, x)
    return accum_value

上面是reduce()的实现函数

reduce函数是化简,第一个参数function是一个二元函数,每次作用在一对元素上,将这对元素执行的结果与序列的下一个元素共同继续被二元函数作用,直观一点就是:

reduce(fun, [1, 2, 3, 4]) = fun(fun(fun(1, 2), 3), 4)

下面简单例子:

>>> def fun(x, y):
…     return x + y

>>> reduce(fun, range(1, 5))
10

而reduce的第三个参数initializer是一个可选的,假如非空,则会作为第一次迭代的第一个元素使用

>>> reduce(fun, range(1, 5), 100)
110

用刚学会的lambda就是:

>>> reduce(lambda x, y: x + y, range(1, 5), 100)
110

同样,盗一张图:

reduce

发表回复