在Python 3中(3.2中引入,能够传递3.3中添加的函数),这已经实现了,在itertools.accumulate。只需像这样使用它:
from itertools import accumulate
list(accumulate([5, 4, 3, 2], lambda a, b: a*b))
# [5, 20, 60, 120]
如果您使用的是早期的Python版本,或者想自己实现它,并且您确实想要任意的lambda
(需要两个参数)才能工作,然后您可以使用上述文档中给出的生成器:
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)
try:
total = next(it)
except StopIteration:
return
yield total
for element in it:
total = func(total, element)
yield total
用法和上面完全一样。
如果您正在使用numpy
,那么存在一个更快的解决方案,至少对于所有numpy.ufunc
s。这些包括与标准库模块基本相同的功能math
提供,然后是一些。您可以找到完整的列表here.
Every numpy.ufunc
有accumulate方法,所以你可以这样做:
import numpy as np
np.multiply.accumulate([5, 4, 3, 2])
# array([ 5, 20, 60, 120])