Python之reduce
2015-11-07 11:03
537 查看
# -*- 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版的ArcGIS栅格计算器模板
- python中的浅拷贝与赋值不同
- python刚入门,还需多努力
- python获取堆栈信息的方法
- Python之filter筛选数据工具
- Vim与Python真乃天作之和
- Windows 7下的python环境配置
- Python之上下文管理器
- python自然语言处理:NLTK+Ubuntu+Eclipse环境配置
- Python实现PointToRaster
- Python编程入门——基础语法详解
- Python 中 return 和 print
- 第二篇、python进阶篇
- Java vs Python
- 使用Python导出Excel图表以及到处为图片的方法
- Python的Flask框架中SQLAlchemy使用时的乱码问题解决
- 用Python的Flask框架结合MySQL些一个内存监控程序
- Vim与Python真乃天作之和
- python 学习爬虫教程~
- python 邮件发送 zabbix 图片