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 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)

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

所以代码需要修改

 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 有三个参数, 第三个参数是初始值的意思,是可有可无的参数。

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

这个仍然也可以用 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模块中

(0)

相关推荐

  • Python中的map()函数和reduce()函数的用法

    Python内建了map()和reduce()函数. 如果你读过Google的那篇大名鼎鼎的论文"MapReduce: Simplified Data Processing on Large Clusters",你就能大概明白map/reduce的概念. 我们先看map.map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回. 举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2,

  • Python中map,reduce,filter和sorted函数的使用方法

    map map(funcname, list) python的map 函数使得函数能直接以list的每个元素作为参数传递到funcname中, 并返回响应的新的list 如下: def sq(x): return x*x #求x的平方 map(sq, [1,3, 5,7,9]) #[1, 9, 25, 49, 81] 在需要对list中的每个元素做转换的时候, 会很方便 比如,把list中的每个int 转换成str map(str, [23,43,4545,324]) #['23', '43',

  • Python中的map、reduce和filter浅析

    1.先看看什么是 iterable 对象 以内置的max函数为例子,查看其doc: 复制代码 代码如下: >>> print max.__doc__max(iterable[, key=func]) -> valuemax(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item.With two or more arguments, return t

  • python用reduce和map把字符串转为数字的方法

    python中reduce和map简介 map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列表来提供返回值:如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表. reduce(func,seq[,init]) :func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:

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

    Python内建了map()和reduce()函数. 如果你读过Google的那篇大名鼎鼎的论文"MapReduce: Simplified Data Processing on Large Clusters",你就能大概明白map/reduce的概念. 我们先看map.map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回. 举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2,

  • python中的reduce内建函数使用方法指南

    官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x

  • Pythont特殊语法filter,map,reduce,apply使用方法

    (1)lambda lambda是Python中一个很有用的语法,它允许你快速定义单行最小函数.类似于C语言中的宏,可以用在任何需要函数的地方. 基本语法如下: 函数名 = lambda args1,args2,...,argsn : expression 例如: add = lambda x,y : x + y print add(1,2) (2)filter filter函数相当于一个过滤器,函数原型为:filter(function,sequence),表示对sequence序列中的每一个

  • 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 sequen

  • python groupby 函数 as_index详解

    在官方网站中对as_index有以下介绍: as_index : boolean, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively "SQL-style" grouped output 翻译过来就是说as_index 的默认值为True, 对于

  • python isinstance函数用法详解

    这篇文章主要介绍了python isinstance函数用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 isinstance() 函数来判断一个对象是否是一个已知的类型类似 type(). isinstance() 与 type() 区别: type() 不会认为子类是一种父类类型,不考虑继承关系. isinstance() 会认为子类是一种父类类型,考虑继承关系. 如果要判断两个类型是否相同推荐使用 isinstance(). 语法

  • Python ord函数()案例详解

    python中ord函数 Python ord()函数 (Python ord() function) ord() function is a library function in Python, it is used to get number value from given character value, it accepts a character and returns an integer i.e. it is used to convert a character to an

  • Python的函数使用详解

    目录 前言 1 跳出循环-break 2 python函数 2.1 内置函数 2.2 自定义函数 2.3 main函数 前言 在两种python循环语句的使用中,不仅仅是循环条件达到才能跳出循环体.所以,在对python函数进行阐述之前,先对跳出循环的简单语句块进行介绍. 1 跳出循环-break python提供了一种方便快捷的跳出循环的方法-break,示例如下,计算未知数字个数的总和: if __name__ == "__main__": sum = 0 while True:

  • Python groupby函数图文详解

    一.分组原理 核心: 1.不论分组键是数组.列表.字典.Series.函数,只要其与待分组变量的轴长度一致都可以传入groupby进行分组. 2.默认axis=0按行分组,可指定axis=1对列分组. groupby()语法格式 DataFrame.groupby(by=None, axis=0, level=None, as_index=True, group_keys=True, squeeze=False, observed=False, **kwargs) groupby原理 group

  • python的函数最详解

    目录 一.函数入门 1.概念 2.定义函数的语法格式 函数名 形参列表 返回值 3.函数的文档(注释→help) 4.举例 二.函数的参数 1.可变对象 2.参数收集(不定个数的参数) 3.解决一个实际问题 4.参数收集(收集关键字参数) 5.逆向参数收集(炸开参数) 6.参数的内存管理 7.函数中变量的作用域 8.获取指定范围内的变量 三.局部函数(函数的嵌套) 四.函数的高级内容 1.函数作为函数的形参 2.使用函数作为返回值 3.递归 五.局部函数与lambda 1.用lambda表达式代

  • 如何利用Python拟合函数曲线详解

    目录 拟合多项式 函数说明 拟合任意函数 函数说明 总结 使用Python拟合函数曲线需要用到一些第三方库: numpy:科学计算的基础库(例如:矩阵) matplotlib:绘图库 scipy:科学计算库 如果没有安装过这些库,需要在命令行中输入下列代码进行安装: pip install numpy matplotlib scipy 拟合多项式 ''' Author: CloudSir Date: 2021-08-01 13:40:50 LastEditTime: 2021-08-02 09:

  • Python help()函数用法详解

    help函数是python的一个内置函数(python的内置函数可以直接调用,无需import),它是python自带的函数,任何时候都可以被使用.help函数能作什么.怎么使用help函数查看python模块中函数的用法,和使用help函数时需要注意哪些问题,下面来简单的说一下. 一.help()函数的作用在使用python来编写代码时,会经常使用python自带函数或模块,一些不常用的函数或是模块的用途不是很清楚,这时候就需要用到help函数来查看帮助.这里要注意下,help()函数是查看函

  • python super()函数的详解

    目录 super的用法 super的原理 总结 Python是一门面向对象的语言,定义类时经常要用到继承,在类的继承中,子类继承父类中已经封装好的方法,不需要再次编写,如果子类如果重新定义了父类的某一方法,那么该方法就会覆盖父类的同名方法,但是有时我们希望子类保持父类方法的基础上进行扩展,而不是直接覆盖,就需要先调用父类的方法,然后再进行功能的扩展,这时就可以通过super来实现对父类方法的调用. super的用法 看下面一个例子: class A: def func(self): print(

随机推荐