数字列表的累积总和

时间:2014-12-02 00:55:13

标签: python

我已经检查过类似的其他问题,但似乎没有人回答我的问题。我需要编写一个函数来返回数字列表的累积和。我有这个,但似乎没有正常工作:

numbers = [4,3,6]

sums = []

def cumulativeSum(numbers):
    for i in range(len(numbers) - 1):
       sums.append(numbers[i] + numbers[i + 1])
    return sums

print cumulativeSum(numbers)       ##[4, 7, 13] What the answers should come out to be

2 个答案:

答案 0 :(得分:1)

这样可以工作,你永远不会访问sum数组,你需要这个数组来增加你先前计算并放入它的值

numbers = [4,3,6]

sums = []

def cumulativeSum(numbers):
    sums.append(numbers[0])
    for i in range(len(numbers) - 1):
        if i == 0:
            sums.append(numbers[i] + numbers[i + 1])
        else:
            sums.append(numbers[i + 1] + sums[i])
    return sums

print cumulativeSum(numbers)

答案 1 :(得分:1)

>>> numbers = [4,3,6]
>>> result = [sum(numbers[:i]) for i in range(1, len(numbers)+1)]
>>> result
[4, 7, 13]