2015-10-17 156 views

回答

5

追加运行总和到列表中的一个循环,并返回名单:

>>> 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 statement

>>> 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与可迭代的默认操作是'运行总和'。或者,您也可以根据需要传递操作员。

+0

这是完美!谢谢。 – arsalunic612

0

DEF运行总和(ALIST): theSum的= 0 累积= [] 对于i在ALIST: theSum的= theSum的+ I cumulative.append(theSum的) 返回累积

+0

该问题已经有一个可接受的答案,您的答案不提供任何新信息 – Guenther

相关问题