`

弄明白python reduce 函数

阅读更多

 

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 itemsof the sequence in the calculation, and serves as a default when thesequence 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, 使用编辑器编写

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

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

 

 

 

 

所以代码需要修改

 

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

 

7 9 行 红色部分就是修改 部分。 通过 help(reduce) 查看 文档,

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)

 

分享到:
评论

相关推荐

    python reduce 函数使用详解

    reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,今天我们就来详细探讨下

    Python reduce函数作用及实例解析

    主要介绍了Python reduce函数作用及实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Python 高级函数实训

    输入一个数,使用reduce计算这个数的阶乘。 实现乘法重载,将两个列表对应元素相乘。 参照课件实例,完成鱼、鸟和水鸟的多继承创建。 类属性和实例属性。 创建一个类,要求内部包含一个用于求和的类方法,一个...

    Python map和reduce函数用法示例

    主要介绍了Python map和reduce函数用法示例,本文给出了两个函数的多个用法示例,需要的朋友可以参考下

    Python reduce()函数的用法小结

    reduce()函数也是Python内置的一个高阶函数。 reduce() 格式: reduce (func, seq[, init()]) reduce()函数即为化简函数,它的执行过程为:每...从reduce函数的执行过程,让我们很容易联想到求一个数的阶乘,而Python中

    Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析

    本文实例讲述了Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法。分享给大家供大家参考,具体如下: 函数的返回值: 函数一旦执行到 return,函数就会结束,并会返回return 后面的值,...

    Python中sorted函数、filter类、map类、reduce函数

    文章目录sorted函数一、sort方法二、sorted内置函数三、情景引入filter类一、简单使用二、练习map类语法:一、简单使用二、练习reduce函数语法:一、简单使用二、设置初始值 Python中使用函数作为参数的内置函数和类...

    使用Python中的reduce()函数求积的实例

    编写一个prod()函数,可以接受一个list并利用reduce()求积。 from functools import reduce def prod(x,y): ... 您可能感兴趣的文章:python reduce 函数使用详解详细分析python3的reduce函数Python reduc

    python中reduce()函数的使用方法示例

    reduce() 函数会对参数序列中元素进行累积,下面这篇文章主要给大家介绍了关于python中reduce()函数的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来...

    详细分析python3的reduce函数

    小编给大家整理了python3的reduce函数详细用法以及相关的技巧,需要的朋友们参考一下吧。

    初学者python笔记(匿名函数、map()函数、reduce()函数、filter()函数)

    本篇是对Python中的匿名函数和map()函数、reduce()函数、filter()函数这四三大封装函数(遍历处理),以及它们的使用案例。 文末是对这几个函数用法功能的比较。 匿名函数 该函数的用法类似于C语言中的宏定义,只是这...

    Python 函数式编程和高阶函数 03高阶函数reduce的使用.mp4

    Python 函数式编程和高阶函数 03高阶函数reduce的使用.mp4

    python中reduce()函数.doc

    Python

    Python lambda表达式filter、map、reduce函数用法解析

    主要介绍了Python lambda表达式filter、map、reduce函数用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    python- 笔记 高阶函数map reduce fileter

    reduce函数:对于序列内所有元素进行累计操作。 filter函数:对于序列中的元素进行筛选,最终获取符合条件的序列。 Tips:这三条函数经常与lambda关键字搭配使用。 一、map() #map在这里我理解翻译为”比对”的意思 ...

    Python中的高级函数map/reduce使用实例

    Python内建了map()和reduce()函数。 如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Processing on Large Clusters”,你就能大概明白map/reduce的概念。 我们先看map。map()函数接收两个参数,...

Global site tag (gtag.js) - Google Analytics