Python之reduce

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#Python之reduce
#http://python.jobbole.com/82597/


#1)reduce语法格式:
'''
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.
'''
#function:函数名,函数自身能接收两个参数,决定了sequence中元素的作用方式,是乘法还是除法等等
#sequence:序列
#initial:累积初始值;如果给出initial, 则第一次传递initial和sequence的第一个元素给function.



#2)reduce具体用法案例
n=4
print reduce(lambda x,y:x*y,range(1,n+1))#24


#等价于:
k=range(1,n+1)
def func(x,y):
    return x*y

print reduce(func,k)#24


#添加第三个参数
n=4
print reduce(lambda x,y:x*y,range(1,n+1),n)#96
#4*1*2*3*4
#首先将第三个参数n和range(1,n+1)的第一个参数传递给func函数。
原文地址:https://www.cnblogs.com/dengyg200891/p/4944716.html