accumulate_Python中的Reduce()与Accumulate()

article/2025/11/5 22:15:34

accumulate

reduce()vs累加 (reduce() vs accumulate)

减少() (reduce())

The functools module is for higher-order functions. Functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.

functools模块用于高阶函数。 作用于或返回其他功能的功能。 通常,就此模块而言,任何可调用对象都可以视为函数。

The functools module provides the following function functools.reduce()

functools模块提供以下功能functools.reduce()

functools.reduce()

functools.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.

将两个参数的函数从左到右累计应用于iterable的项,以将iterable减少为单个值。

functools.reduce(function, iterable,initializer)

functools. reduce ( function , iterable,initializer )

If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty.

如果存在可选的initializer值设定项,则将其放在计算中可迭代项的前面,并在可迭代项为空时用作默认值。

If initializer is not given and iterable contains only one item, the first item is returned.

如果未给出initializer值设定项,并且iterable仅包含一项,则返回第一项。

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

示例: reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

Image for post
Image Source: Author
图片来源:作者

Example 1: Find the product of the list elements using reduce()

示例1:使用reduce()查找列表元素的乘积

from functools import reduce
l1=[1,2,3,4,5]
l2=reduce(lambda x,y:x*y,l1)
print (l2)#Output:120

Example 2:Find the largest number in the iterable using reduce()

示例2:使用reduce()查找可迭代的最大数字

from functools import reduce
l1=[15,12,30,4,5]
l2=reduce(lambda x,y: x if x>y else y,l1)
print (l2)#Output:30

图示: (Pictorial representation:)

Image for post
Image Source: Author
图片来源:作者

Example 3:Using User-defined function in reduce()

示例3:在reduce()中使用用户定义的函数

from functools import reducedef sum1(x,y):
return x+y
l1=[15,12,30,4,5]
l2=reduce(sum1,l1)
print (l2)#Output:66

Example 4: Initializer is mentioned.

示例4:提到初始化程序。

If the optional initializer is present, it is placed before the items of the iterable in the calculation.

如果存在可选的initializer程序,则将其放在计算中可迭代项的前面。

from functools import reducedef sum1(x,y):
return x+y
l1=[1,2,3,4,5]
l2=reduce(sum1,l1,10)
print (l2)#Output:25

Example 5:Iterable contains only one item, reduce() will return that item.

示例5:Iterable仅包含一项,reduce()将返回该项。

from functools import reducedef sum1(x,y):
return x+y
l1=[5]
l2=reduce(sum1,l1)
print (l2)#Output:5from functools import reduce
l1=[15]
l2=reduce(lambda x,y: x if x>y else y,l1)
print (l2)#Output:15

Example 6: If iterable is empty and the initializer is given, reduce() will return the initializer.

示例6:如果iterable为空,并且给出了初始化程序,则reduce()将返回初始化程序。

from functools import reducedef sum1(x,y):
return x+y
l1=[]
l2=reduce(sum1,l1,10)
print (l2)#Output:10

itertools.accumulate() (itertools.accumulate())

Makes an iterator that returns accumulated sum or accumulated results of other binary functions which is mentioned in func-parameter.If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func.-Python documentation

生成一个迭代器,该迭代器返回func-parameter中提到的其他二进制函数的累加和或累加结果。如果提供了func ,则它应该是两个参数的函数。 可迭代输入的元素可以是可以接受为func参数的任何类型。- Python文档

itertools.accumulate(iterable[, func, *, initial=None])

itertools. accumulate ( iterable [, func , * , initial=None ])

Example 1:By using itertools.accumulate(), we can find the running product of an iterable. The function argument is given as operator.mul.

示例1:通过使用itertools.accumulate(),我们可以找到iterable的运行产品。 函数参数作为operator.mul给出。

It will return an iterator that yields all intermediate values. We can convert to list by using a list() constructor.

它将返回产生所有中间值的迭代器。 我们可以使用list()构造函数转换为list。

from itertools import accumulateimport operator
l2=accumulate([1,2,3,4,5],operator.mul)
print (list(l2))#Output:[1, 2, 6, 24, 120]

Pictorial Representation.

绘画作品。

Image for post
Photo by Author
作者照片

Example 2: If the function parameter is not mentioned, by default it will perform an addition operation

示例2:如果未提及功能参数,则默认情况下它将执行加法运算

It will return an iterator that yields all intermediate values. We can convert to list by using list() constructor.

它将返回产生所有中间值的迭代器。 我们可以使用list()构造函数转换为列表。

import itertools
#using add operator,so importing operator moduleimport operator
l1=itertools.accumulate([1,2,3,4,5])
print (l1)#Output:<itertools.accumulate object at 0x02CD94C8>
#Converting iterator to list object.
print (list(l1))#Output:[1, 3, 6, 10, 15]#using reduce() for same functionfrom functools import reduce
r1=reduce(operator.add,[1,2,3,4,5])
print (r1)#Output:15

Example 3:Function argument is given as max(), to find a running maximum

示例3:函数参数以max()的形式给出,以查找运行最大值

from itertools import accumulate
l4=accumulate([2,4,6,3,1],max)
print (list(l4))#Output:[2, 4, 6, 6, 6]

Example 4: If the initial value is mentioned, it will start accumulating from the initial value.

例4:如果提到了初始值,它将从初始值开始累加。

from itertools import accumulateimport operator

#If initial parameter is mentioned, it will start accumulating from the initial value.
#It will contain more than one element in the ouptut iterable.
l2=accumulate([1,2,3,4,5],operator.add,initial=10)
print (list(l2))#Output:[10, 11, 13, 16, 20, 25]

Example 5: If the iterable is empty and the initial parameter is mentioned, it will return the initial value.

示例5:如果iterable为空,并且提到了初始参数,它将返回初始值。

from itertools import accumulateimport operatorl2=accumulate([],operator.add,initial=10)
print (list(l2))#Output:[10]

Example 6: If iterable contains one element and the initial parameter is not mentioned, it will return that element.

示例6:如果iterable包含一个元素,并且未提及初始参数,它将返回该元素。

from itertools import accumulate
l2=accumulate([5],lambda x,y:x+y)
print (list(l2))#Output:[5]

Example 7: Iterating through the iterator using for loop

示例7:使用for循环遍历迭代器

Return type is an iterator. We can iterate through iterator using for loop also.

返回类型是一个迭代器。 我们也可以使用for循环遍历迭代器。

from itertools import accumulate
l2=accumulate([5,6,7],lambda x,y:x+y)for i in l2:
print (i)
'''
Output:
5
11
18
'''

reduce()和accumulate()之间的区别 (Differences between reduce() and accumulate())

Image for post
Image Source: Author
图片来源:作者

结论: (Conclusion:)

  • reduce() function is supported by the functools module.

    functools模块支持reduce()函数。

  • accumulate() function is supported by the itertools module.

    itertools模块支持accumulate()函数。

  • reduce() will return only an accumulated value.

    reduce()将仅返回一个累加值

  • accumulate() will return the running accumulated value. Like we can find running max, running product, running sum of an iterable using the accumulate() function.

    accumulate()将返回运行的累积值 。 就像我们可以使用accumulate()函数找到运行的最大值,运行的产品,可迭代的运行总和。

  • accumulate() returns an iterator.

    accumulate()返回一个迭代器。

Thank you for reading my article, I hope you found it helpful!

感谢您阅读我的文章,希望对您有所帮助!

资源(Python文档): (Resources(Python Documentation):)

functools module

functools模块

functools.reduce

functools.reduce

itertools.accumulate

itertools.accumulate

翻译自: https://codeburst.io/reduce-vs-accumulate-in-python-3ecee4ee8094

accumulate


http://chatgpt.dhexx.cn/article/RkqfMFhJ.shtml

相关文章

std库学习②:accumulate

该算法在numeric头文件中定义。 首先来看一个例子&#xff1a; //定义了一个整型vector数组 vector<int> vec {2, 0, 12, 3, 5, 0, 2, 7, 0, 8}; 按标准版的accumulate来使用&#xff0c;如下&#xff1a; std::accumulate(vec.begin(),vec.end(),35); 上面的代码语…

数值算法之accumulate

一、接口实现 功能&#xff1a;计算区间[first&#xff0c;second)内所有元素和_Val&#xff08;初始值&#xff09;的总和。 template<class _InIt,class _Ty,class _Fn2> inline_Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func){ // return sum of…

可可丝大战科克斯

来&#xff0c;大家和我一起大声朗读&#xff1a; 餐厅里坐着个可可丝&#xff0c;吃着一盘炒肉丝&#xff1b; 客厅里躺着个科克斯&#xff0c;听着一盘碧昂斯。 听碧昂斯的科克斯要可可丝放下肉丝专心欣赏碧昂斯&#xff0c; 吃肉丝的可可丝要科克斯放下碧昂斯赶紧来吃肉丝。…

布莱克斯科尔斯模型(六)写在最后

春节前后大时间概花了不到一个月在研究BS方程&#xff0c;因为工作中要用到股指期货delta对冲&#xff0c;对于方程怎么推导怎么求解大致明白了。 曾经这个公式让两个人获得诺贝尔经济学奖&#xff0c;也曾经让一家非常豪华的对冲基金破产。 长期资本&#xff11; 聪明的代价&…

布莱克斯科尔斯模型(五) 方程求解过程

布莱克斯科尔斯模型&#xff08;五) 方程求解过程 posted on 2019-02-12 20:05 luoganttcc 阅读(...) 评论(...) 编辑 收藏

布莱克斯科尔斯模型(二)之e^(-βt^2)的傅里叶变换

的傅里叶变换和逆变换在求解热传导方程时非常重要&#xff0c;而热传导方程&#xff0c;又是求解BS方程的基础 详细证明

卢卡斯·巴斯克斯

目录 卢卡斯巴斯克斯 卢卡斯巴斯克斯 卢卡斯巴斯克斯&#xff08;Lucas Vzquez&#xff09;&#xff0c;1991年7月1日出生于西班牙柯蒂斯&#xff0c;西班牙足球运动员&#xff0c;司职右边锋&#xff0c;可兼任中场&#xff0c;效力于西甲皇家马德里足球俱乐部。 2007年&#…

凭期权定价捧得诺奖的斯科尔斯败走麦城,理论好对于交易有帮助吗?

这篇文章要讲述的是成立于1994年2月的美国长期资本管理公司&#xff08;Long-Term Capital Management&#xff0c;LTCM&#xff09;。 斯科尔斯 这家公司的管理层可都是金融圈声名赫赫的大佬。掌门是被誉为能“点石成金”的华尔街债务套利之父梅里韦瑟&#xff08;John Meriwe…

戴维·考克斯爵士去世

得知上个世纪最重要的统计学家之一戴维考克斯爵士去世&#xff0c;我们深感悲痛。 大卫爵士因其在统计学和应用概率方面的开创性工作而享誉国际&#xff0c;包括开发 Cox 模型&#xff0c;该模型被广泛用于生存数据分析&#xff0c;并帮助研究人员更轻松地识别死亡率和其他生存…

柯布-道格拉斯生产函数

柯布-道格拉斯生产函数&#xff08;Cobb–Douglas production function&#xff09;最初是美国数学家查尔斯柯布&#xff08;Charles Wiggins Cobb&#xff09;和经济学家保罗道格拉斯&#xff08;Paul Howard Douglas&#xff09;在探讨投入和产出的关系时共同创造的。 在柯布…

克鲁斯卡尔

版权声明&#xff1a;这就是我的文章啊 这一个算法。有点厉害。 首先&#xff0c;输入一个图&#xff0c;然后求它的最小生成树&#xff08;即一条最短的链&#xff0c;联通N个顶点&#xff09;。 (这就是图) 好的&#xff0c;然后&#xff0c;我们首先观察这个图&#xff0c;发…

kruskalCase克鲁斯卡尔算法

介绍 它的特点和Prim算法不一样&#xff0c;Prim是以点为主&#xff0c;通过顶点遍历没有访问的节点计算最小权重直至一条最小边出来&#xff1b;而Kruskal算法是以边为主&#xff0c;时间复杂度要低一些0(edge); 什么是最小生成树 最小生成树&#xff1a;在一个有n个结点的…

第19章 随机波动率模型入门

这学期会时不时更新一下伊曼纽尔德曼&#xff08;Emanuel Derman&#xff09; 教授与迈克尔B.米勒&#xff08;Michael B. Miller&#xff09;的《The Volatility Smile》这本书&#xff0c;本意是协助导师课程需要&#xff0c;发在这里有意的朋友们可以学习一下&#xff0c;思…

欧内斯特·卢瑟福

Ernest Rutherford BiographyKathy老师讲述的有趣科学历史 01 欧内斯特卢瑟福 一、背景介绍 欧内斯特卢瑟福因其通过金箔实验发现了原子核而闻名于世。 实际上他的工作远多于此&#xff0c;甚至在他发现原子核之前就发现了几种不同形式的发射性、 发现化学元素可以衰变成其它…

クレス / 克雷斯

目录 基本资料面板值&#xff08;无天冥加成&#xff09;天冥奖励 战斗宣言&#xff08;VC&#xff09;技能珠子 回到人物索引 基本资料 NS(4~5★)协奏3入队 (Ver 2.7.50)時空剣士の史籍&#xff08;火精灵试炼报酬&#xff09; 天冥属性武器防具属性耐性异常耐性NS天火剑护…

改变世界的 17 个方程式( 17 Equations that Changed the World)

目录 勾股定理 对数 微积分 万有引力定律 复数 多面体欧拉定理 正态分布 波动方程 傅里叶变换 纳维-斯托克斯方程 麦克斯韦方程组 热力学第二定律 相对论 薛定谔方程 信息理论 混沌理论 布莱克-斯科尔斯公式 2013年&#xff0c;英国数学家伊恩斯图尔特&#x…

十二、计算期权定价和布莱克-斯科尔斯公式

期权定价 期权定价(Option Valuation),期权价值的两个基本构成要素是:内含价值和时间价值。 期权定价,内含价值,也称内在价值,是期权持有人因通过行权获得股票而不是直接购买股票而实现的收益。 布莱克-斯科尔斯公式 1997年10月10日,第二十九届诺贝尔经济学奖授予了…

布莱克—斯科尔斯—默顿(BSM)模型

BSM模型是最常用的期权定价模型之一&#xff0c;虽然其假设不合符市场事实&#xff0c;但是该模型的提出奠定了现代金融衍生品法则的基石。该模型在学界的发展&#xff1a;早期的期权定价大多采用Black-Scholes(B-S)期权定价模型&#xff0c;B-S模型假定标的资产收益率服从正态…