首页 > 编程语言 > 详细

Python之reduce

时间:2015-11-07 12:11:39      阅读:407      评论:0      收藏:0      [点我收藏+]
# -*- 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函数。

 

Python之reduce

原文:http://www.cnblogs.com/dengyg200891/p/4944716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!