python中reduce函数详解

您所在的位置:网站首页 python中reverse函数有什么用 python中reduce函数详解

python中reduce函数详解

2024-07-17 13:11:26| 来源: 网络整理| 查看: 265

1、python2 中,reduce函数是内置函数

2、python3 中,函数被移到了functools模块中

3、官方文档:

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 参数,计算时它将被放在序列的所有项前面,如果序列是空的,它也就是计算的默认结果值了

 

4、解释:

reduce有三个参数:

function:有两个参数的额函数,           必需参数sequence: 元组、列表等可迭代对象,  必需参数inital: 初始值,                                     可选参数

 

5、reduce的工作过程是:

在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的过程中,

首先把 前两个元素传给 函数参数,函数加工后,然后把得到的结果和第三个元素作为两个参数传给函数参数,函数加工后得到的结果又和第四个元素作为两个参数传给函数参数,依次类推

如果传入了 initial 值, 那么首先传的就不是 sequence 的第一个和第二个元素,而是 initial值和 第一个元素。

经过这样的累计计算之后合并序列到一个单一返回值

 

7、初阶1

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

其实就相当于 1 + 2 + 3 + 4 = 10, 如果把加号改成乘号, 就成了阶乘了

当然 仅仅是求和的话还有更简单的方法,

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

 

8、初阶2

把一个整数列表拼成整数:

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

 

9、进阶1

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['age'] + value['age'] return sum total_age = reduce(reducer, scientists) print(total_age) 'int' object is not subscriptable

错误分析:

第一轮循环时:accumulator =  {'name':'Alan Turing', 'age':105}

                          value =            {'name':'Dennis Ritchie', 'age':76}

第二轮循环时:accumulator =  sum = 105 + 76 = 181

                          value           =  {'name':'John von Neumann', 'age':114}

所以报错,如下图:

 

 修改:

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)

结果:

467

分析:

reduce 有三个参数, 第三个参数是初始值的意思,是可有可无的参数。

 

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

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

 

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

 

10、进阶2

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']}

 

 

参考:

https://www.cnblogs.com/lonkiss/p/understanding-python-reduce-function.html



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


    图片新闻

    实验室药品柜的特性有哪些
    实验室药品柜是实验室家具的重要组成部分之一,主要
    小学科学实验中有哪些教学
    计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
    实验室各种仪器原理动图讲
    1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
    高中化学常见仪器及实验装
    1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
    微生物操作主要设备和器具
    今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
    浅谈通风柜使用基本常识
     众所周知,通风柜功能中最主要的就是排气功能。在

    专题文章

      CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭