Python - 递归总和列表

时间:2016-10-12 21:54:44

标签: python list recursion sum

如何使用Python生成一个列表,其中每个元素都是前一个数字的总和。

以下是一个例子:

input: [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]

25690.16 + -34010.61 = -8320.45
-8320.45 + 9278.44 = -8320.45
957.99 + -808.00 = 149.99
149.99 + -2126.95 = -1976.96
-1976.96 + 3920.19 = 1943.23
1943.23 + -1793.23 = 150
150 + 997.54 = 1147.54
1147.54 + -1142.55 = 4.99
4.99 + -69349.58 = -69344.54

output: [ 25690.16, -8320.45, -8320.45, 149.99, -1976.96, 1943.23, 150, 1147.54, 4.99, -69344.54 ]

5 个答案:

答案 0 :(得分:2)

使用itertools.accumulate

>>> from itertools import accumulate
>>> l = [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]
>>> list(accumulate(l))
[25690.16, -8320.45, 957.9899999999998, 149.98999999999978, -1976.96, 1943.23, 150.0, 1147.54, 4.990000000000009, -69344.59]

这通常比numpy.cumsum

的替代方案更快
>>> from numpy import cumsum
>>> l = [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]
>>> cumsum(l)
array([  2.56901600e+04,  -8.32045000e+03,   9.57990000e+02,
         1.49990000e+02,  -1.97696000e+03,   1.94323000e+03,
         1.50000000e+02,   1.14754000e+03,   4.99000000e+00,
        -6.93445900e+04])

答案 1 :(得分:1)

不使用导入:

>>> l = [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]
>>> o = [l[0]]
>>> for x in l[1:]:
>>>     o.append(x+o[-1])
>>> print(o)    
[25690.16, -8320.45, 957.9899999999998, 149.98999999999978, -1976.96, 1943.23, 150.0, 1147.54, 4.990000000000009, -69344.59]

答案 2 :(得分:0)

迭代方法

L = [1,2,3,4,5,6]
N = []
for i in range(1,len(L)+1):
    N.append(sum(L[:i]))
print(N)

希望这会有所帮助

答案 3 :(得分:0)

def sum_list(l):
    L = [sum(l[:i+1]) for i in range(len(l))]
    return L

答案 4 :(得分:0)

我认为你想要这样的东西:

l = [1,2,3,4,5]
l2 = []
l2.append(l[0])
aux = l[0]
i = 0
while i < len(l):
    if i+1 < len(l):
        l2.append(aux + l[i+1])
        aux=l[i+1]
    i=i+1

print (l2)