手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python的functools.reduce用法

[日期:2016-02-17] 来源:Linux社区  作者:alan-babyblog [字体:大 中 小]

Python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import 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.

意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

from functools import reduce

reduce(lambda x,y: x+y, [1, 2, 3])

输出 6

reduce(lambda x, y: x+y, [1,2,3], 9)

输出 15

reduce(lambda x,y: x+y, [1, 2, 3], 7) 

输出 13 


*functool标准库还有很多功能,可以参考网上的资料

下面关于Python的文章您也可能喜欢,不妨看看:

Linux下Python的安装以及注意事项  http://www.linuxidc.com/Linux/2015-11/124861.htm

Ubuntu 14.04 下安装使用Python rq模块  http://www.linuxidc.com/Linux/2015-08/122441.htm

无需操作系统直接运行 Python 代码  http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍:请点这里
Python 的下载地址:请点这里 

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-02/128438.htm

linux
相关资讯       Python用法  functools.reduce 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款