# Python 3.1 or before
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
5条答案
按热度按时间pobjuy321#
在Python 3中,我们可以使用
itertools.accumulate()
:Accumulate生成将输入可迭代对象的值相加的运行结果,从第一个值开始:
您可以传入另一个操作作为第二个参数;这应该是一个接受累加结果和下一个值的可调用函数,返回新的累加结果。
operator
module在为这类工作提供标准数学运算符方面非常有帮助;你可以用它来产生一个连续的乘法结果,例如:这个功能很容易移植到旧版本(Python 2、Python 3.0或Python 3.1):
fivyi3re2#
由于您已经在使用
numpy
,因此可以使用cumsum
:vfhzx4xs3#
好吧,你说你不想要
numpy
,但这是我的解决方案。在我看来,你只是简单地取累积和,因此使用cumsum()
函数。举个随机的例子
fwzugrvs4#
这里有一个概念滥用了python 3.8中引入的:=“walrus operator”的初衷。它将变量作为更大表达式的一部分进行赋值。我对这个概念的印象是,它的意图是保存用户在“if”的测试部分进行计算,然后在可执行部分再次进行计算。但是它不是if的本地变量,因此在定义变量之后,您可以随时使用它。因此,这个方法在列表解析中使用一个始终为True的if,作为进行重新赋值的位置。不幸的是,“+:=”不是一个运算符,因此您必须进行长手加法赋值,而不是+=:
xmjla07d5#
对上述答案的更新,找到了一个更简单,更好的方法。不知道为什么我之前没有想到。使用海象操作符:=的项目总是包含在()中,有一个返回,不像常规赋值。所以在命令行中,test=0静默执行,但(test:=0)将0打印到屏幕上。所以在这方面,它就像一个函数,因为它有一个返回。所以它可以进入列表压缩的内容部分,而不是在带有或True的一次性“if”中使用它。
所以代码变为: