Python - recursive sum list [duplicate]

2019-04-16 19:52发布

问题:

This question already has an answer here:

  • How to find the cumulative sum of numbers in a list? 18 answers

How to generate a list with Python in which each element is the sum of the previous numbers.

Here's an example:

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 ]

回答1:

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

This is generally faster than the alternative of 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])


回答2:

Without using imports:

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


回答3:

iterative method

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

hope this helps



回答4:

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


回答5:

I Think that you want something like this:

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)