在 Python 3 中,你可以使用itertools.accumulate():
from itertools import accumulate
array = list(accumulate(rand(100)))
Accumulate 产生将输入可迭代的值相加的运行结果,从第一个值开始:
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
您可以传入不同的操作作为第二个参数;这应该是一个可调用的,它获取累积结果和下一个值,返回新的累积结果。这operator module对于为此类工作提供标准数学运算符非常有帮助;您可以使用它来产生运行乘法结果,例如:
>>> import operator
>>> list(accumulate(range(1, 10), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
该功能很容易向后移植到旧版本(Python 2、Python 3.0 或 3.1):
# 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