python reduce 函数使用详解


Posted in Python onDecember 05, 2017

reduce() 函数在 python 2 是内置函数, 从python 3 开始移到了 functools 模块。

官方文档是这样介绍的

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.

从左到右对一个序列的项累计地应用有两个参数的函数,以此合并序列到一个单一值。

例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])  计算的就是((((1+2)+3)+4)+5)。

如果提供了 initial 参数,计算时它将被放在序列的所有项前面,如果序列是空的,它也就是计算的默认结果值了

嗯, 这个文档其实不好理解。看了还是不懂。 序列 其实就是python中 tuple  list  dictionary string  以及其他可迭代物,别的编程语言可能有数组。

reduce 有 三个参数

function 有两个参数的函数, 必需参数
sequence tuple ,list ,dictionary, string等可迭代物,必需参数
initial 初始值, 可选参数

reduce的工作过程是 :在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的过程中,首先把 前两个元素传给 函数参数,函数加工后,然后把得到的结果和第三个元素作为两个参数传给函数参数, 函数加工后得到的结果又和第四个元素作为两个参数传给函数参数,依次类推。 如果传入了 initial 值, 那么首先传的就不是 sequence 的第一个和第二个元素,而是 initial值和 第一个元素。经过这样的累计计算之后合并序列到一个单一返回值

 reduce 代码举例,使用REPL演示

>>> def add(x, y):
...   return x+y
...
>>> from functools import reduce
>>> reduce(add, [1,2,3,4])
10
>>>

上面这段 reduce 代码,其实就相当于 1 + 2 + 3 + 4 = 10, 如果把加号改成乘号, 就成了阶乘了
当然 仅仅是求和的话还有更简单的方法,如下

>>> sum([1,2,3,4])
10
>>>

很多教程只讲了一个加法求和,太简单了,对新手加深理解还不够。下面讲点更深入的例子

还可以把一个整数列表拼成整数,如下

>>> from functools import reduce
>>> reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5])
12345
>>>

对一个复杂的sequence使用reduce ,看下面代码,更多的代码不再使用REPL, 使用编辑器编写

from functools import reduce
 scientists =({'name':'Alan Turing', 'age':105},
       {'name':'Dennis Ritchie', 'age':76},
       {'name':'John von Neumann', 'age':114},
       {'name':'Guido van Rossum', 'age':61})
 def reducer(accumulator , value):
   sum = accumulator['age'] + value['age']
   return sum
 total_age = reduce(reducer, scientists)
 print(total_age)

这段代码会出错,看下图的执行过程

python reduce 函数使用详解

所以代码需要修改

from functools import reduce
 scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
       {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
       {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
       {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
 def reducer(accumulator , value):
   sum = accumulator + value['age']
   return sum
 total_age = reduce(reducer, scientists, 0)
 print(total_age)

7, 9 行 红色部分就是修改 部分。 通过 help(reduce) 查看 文档,
reduce 有三个参数, 第三个参数是初始值的意思,是可有可无的参数。

修改之后就不出错了,流程如下

python reduce 函数使用详解

这个仍然也可以用 sum 来更简单的完成

sum([x['age'] for x in scientists ])

做点更高级的事情,按性别分组

from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
       {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
       {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
       {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def group_by_gender(accumulator , value):
  accumulator[value['gender']].append(value['name'])
  return accumulator
grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]})
print(grouped)

输出

{'male': ['Alan Turing', 'Dennis Ritchie'], 'female': ['Ada Lovelace', 'Frances E. Allen']}

可以看到,在 reduce 的初始值参数传入了一个dictionary,, 但是这样写 key 可能出错,还能再进一步自动化,运行时动态插入key

修改代码如下

grouped = reduce(group_by_gender, scientists, collections.defaultdict(list))

当然 先要 import  collections 模块

这当然也能用 pythonic way 去解决

import itertools
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
       {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
       {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
       {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
grouped = {item[0]:list(item[1])
      for item in itertools.groupby(scientists, lambda x: x['gender'])}
print(grouped)

再来一个更晦涩难懂的玩法。工作中要与其他人协作的话,不建议这么用,与上面的例子做同样的事,看不懂无所谓。

from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
       {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
       {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
       {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
grouped = reduce(lambda acc, val: {**acc, **{val['gender']: acc[val['gender']]+ [val['name']]}}, scientists, {'male':[], 'female':[]})
print(grouped)

**acc, **{val['gneder']...   这里使用了 dictionary merge syntax ,  从 python 3.5 开始引入, 详情请看 PEP 448 - Additional Unpacking Generalizations  怎么使用可以参考这个 python - How to merge two dictionaries in a single expression? - Stack Overflow

python 社区推荐写可读性好的代码,有更好的选择时不建议用reduce,所以 python 2 中内置的reduce 函数 移到了 functools模块中

Python 相关文章推荐
Python单元测试框架unittest使用方法讲解
Apr 13 Python
Python使用Srapy框架爬虫模拟登陆并抓取知乎内容
Jul 02 Python
浅谈Python基础之I/O模型
May 11 Python
有趣的python小程序分享
Dec 05 Python
Python找出最小的K个数实例代码
Jan 04 Python
VSCode下配置python调试运行环境的方法
Apr 06 Python
Python解析Excle文件中的数据方法
Oct 23 Python
Python for循环与getitem的关系详解
Jan 02 Python
下载与当前Chrome对应的chromedriver.exe(用于python+selenium)
Jan 14 Python
Matplotlib自定义坐标轴刻度的实现示例
Jun 18 Python
scrapy-splash简单使用详解
Feb 21 Python
Python编程super应用场景及示例解析
Oct 05 Python
有趣的python小程序分享
Dec 05 #Python
详细分析python3的reduce函数
Dec 05 #Python
Python数据可视化正态分布简单分析及实现代码
Dec 04 #Python
Python编程实现二分法和牛顿迭代法求平方根代码
Dec 04 #Python
Python编程给numpy矩阵添加一列方法示例
Dec 04 #Python
Python实现返回数组中第i小元素的方法示例
Dec 04 #Python
Python实现基本数据结构中队列的操作方法示例
Dec 04 #Python
You might like
PHP的一个完美GIF等比缩放类,附带去除缩放黑背景
2014/04/01 PHP
护卫神php套件 php版本升级方法(php5.5.24)
2015/05/10 PHP
详解PHP中的Traits
2015/07/29 PHP
PHP内置加密函数详解
2016/11/20 PHP
PHP进阶学习之依赖注入与Ioc容器详解
2019/06/19 PHP
PHP使用ajax的post方式下载excel文件简单示例
2019/08/06 PHP
浅谈PHP5.6 与 PHP7.0 区别
2019/10/09 PHP
基于jquery的一个OutlookBar类,动态创建导航条
2010/11/19 Javascript
jquery 追加tr和删除tr示例代码
2013/09/12 Javascript
jquery滚动特效集锦
2015/06/03 Javascript
nodejs操作mongodb的填删改查模块的制作及引入实例
2018/01/02 NodeJs
element ui里dialog关闭后清除验证条件方法
2018/02/26 Javascript
js使用formData实现批量上传
2020/03/27 Javascript
jQuery选择器之基本选择器用法实例分析
2019/02/19 jQuery
vue使用svg文件补充-svg放大缩小操作(使用d3.js)
2020/09/22 Javascript
ant-design-vue 时间选择器赋值默认时间的操作
2020/10/27 Javascript
浅析Python3爬虫登录模拟
2018/02/07 Python
Numpy数据类型转换astype,dtype的方法
2018/06/09 Python
selenium + python 获取table数据的示例讲解
2018/10/13 Python
python 字典操作提取key,value的方法
2019/06/26 Python
Windows10下 python3.7 安装 facenet的教程
2019/09/10 Python
解决python 上传图片限制格式问题
2019/10/30 Python
Django框架创建项目的方法入门教程
2019/11/04 Python
Window系统下Python如何安装OpenCV库
2020/03/05 Python
python数据处理——对pandas进行数据变频或插值实例
2020/04/22 Python
Django扫码抽奖平台的配置过程详解
2021/01/14 Python
django项目中使用云片网发送短信验证码的实现
2021/01/19 Python
SportsDirect.com新加坡:英国第一体育零售商
2019/03/30 全球购物
物业管理毕业生个人的求职信
2013/11/30 职场文书
我们的节日清明节活动方案
2014/03/05 职场文书
奖学金感谢信
2015/01/21 职场文书
如何写通讯稿
2015/07/22 职场文书
关于开学的感想
2015/08/10 职场文书
《一面五星红旗》教学反思
2016/02/23 职场文书
windows安装python超详细图文教程
2021/05/21 Python
win10如何快速切换窗口 win10切换窗口快捷键分享
2022/07/23 数码科技