Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Running Sum in List [duplicate]

Given the following list:

a=[1,2,3]

I'd like to generate a new list where each number is the sum of it and the values before it, like this:

result = [1,3,6]

Logic:

1 has no preceding value, so it stays the same.

3 is from the first value (1) added to the value of the second number in the list (2)

6 is from the sum of 1 and 2 from the first two elements, plus the third value of 3.

Thanks in advance!

like image 416
Dance Party Avatar asked Dec 30 '16 05:12

Dance Party


2 Answers

Python 3 has itertools.accumulate for exactly this purpose:

>>> from itertools import accumulate
>>> a=[1,2,3]
>>> list(accumulate(a))
[1, 3, 6]
like image 135
niemmi Avatar answered Sep 19 '22 04:09

niemmi


If you'd like a numpy solution

from numpy import cumsum
result = list(cumsum(a))
like image 41
gsmafra Avatar answered Sep 22 '22 04:09

gsmafra