您可以使用它,如果它更优雅:
def scanl(f, base, l):
for x in l:
base = f(base, x)
yield base
像这样使用它:
import operator
list(scanl(operator.add, 0, range(1,11)))
Python 3.x具有itertools.accumulate(iterable, func= operator.add)
。它的实现如下。该实现可能会给您一些想法:
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