更新时间:2022-04-01 05:11:12
你可以使用这个,如果它更优雅:
You can use this, if its more elegant:
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)
.它的实现如下.实施可能会给你一些想法:
Python 3.x has itertools.accumulate(iterable, func= operator.add)
. It is implemented as below. The implementation might give you ideas:
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