在循环中将运行总和添加到列表中并返回该列表:
>>> def running_sum(iterable):
... s = 0
... result = []
... for value in iterable:
... s += value
... result.append(s)
... return result
...
>>> running_sum([1,2,3,4,5])
[1, 3, 6, 10, 15]
或者,使用 yield
语句:
>>> def running_sum(iterable):
... s = 0
... for value in iterable:
... s += value
... yield s
...
>>> running_sum([1,2,3,4,5])
<generator object runningSum at 0x0000000002BDF798>
>>> list(running_sum([1,2,3,4,5])) # Turn the generator into a list
[1, 3, 6, 10, 15]
如果您使用的是Python 3.2及以上版本,您可以使用
itertools.accumulate
。
>>> import itertools
>>> list(itertools.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]
accumulate
函数的默认操作是对可迭代对象进行“累加求和”。可以根据需要选择性地传递一个运算符。
numpy.cumsum
已经为你做好了呢? - jadelord