一个以整数列表为参数并返回连续总和列表的函数。

4

我有一个Python函数,它可以计算列表中所有整数的和。

def runningSum(aList):
    theSum = 0
    for i in aList:
        theSum = theSum + i
    return theSum

结果:

>>runningSum([1,2,3,4,5]) = 15

我希望通过这个函数达到的目的是返回一个运行总数列表,就像这样:

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] 

为什么要重复造轮子,当numpy.cumsum已经为你做好了呢? - jadelord
2个回答

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 语句

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

定义 runningSum(aList) 函数: theSum = 0 cumulative = [ ] for i in aList: theSum = theSum + i cumulative.append(theSum) return cumulative


该问题已有接受的答案,您的回答没有提供任何新信息。 - Guenther

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接