ars*_*612 4 python function python-2.7
我在python中有这个函数,这个函数计算列表中整数的总和.
def runningSum(aList):
theSum = 0
for i in aList:
theSum = theSum + i
return theSum
Run Code Online (Sandbox Code Playgroud)
结果:
>>runningSum([1,2,3,4,5]) = 15
Run Code Online (Sandbox Code Playgroud)
我希望从这个函数中获得的是返回一个运行总计列表.这样的事情:
E.g.: [1,2,3,4,5] -> [1,3,6,10,15]
E.g.: [2,2,2,2,2,2,2] -> [2,4,6,8,10,12,14]
Run Code Online (Sandbox Code Playgroud)
将运行总和追加到循环中的列表中并返回列表:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
或者,使用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]
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 3.2+,则可以使用itertools.accumulate.
>>> import itertools
>>> list(itertools.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]
Run Code Online (Sandbox Code Playgroud)
其中accumulate使用iterable 的默认操作是'running sum'.您也可以选择根据需要传递运算符.