函数编程--reduce()

来源:互联网 发布:深圳万户网络 编辑:程序博客网 时间:2024/05/18 03:43

>>> help(reduce)
Help on built-in function reduce in module __builtin__:

reduce(...)
    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 the
    sequence is empty.

>>> l=[1,2,3,4,5,6,7]
>>> reduce(lambda x,y:x+y,l)
28
>>> reduce(lambda x,y:x+y,l,2)
30