【问题标题】:a function that takes a list of integers as a parameter and returns a list of running totals将整数列表作为参数并返回运行总计列表的函数
【发布时间】:2015-10-17 06:27:06
【问题描述】:

我在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 为你做这件事时,为什么要重新发明轮子?

标签: python function python-2.7


【解决方案1】:

将运行总和附加到循环中的列表中并返回列表:

>>> 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 中带有可迭代的默认操作是“运行总和”。您也可以根据需要传递运算符。

【讨论】:

    【解决方案2】:

    def runningSum(aList): 总和 = 0 累积 = [ ] 对于列表中的 i: theSum = theSum + i 累积的.append(theSum) 返回累积

    【讨论】:

    • 该问题已有一个可接受的答案,而您的答案没有提供任何新信息
    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2015-03-24
    • 2021-03-15
    • 1970-01-01
    相关资源
    最近更新 更多