Accumulate function in python

sturlamolden sturlamolden at yahoo.no
Tue Jul 27 09:51:21 EDT 2010


On 19 Jul, 13:18, dhruvbird <dhruvb... at gmail.com> wrote:
> Hello,
>   I have a list of integers: x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
>   And would like to compute the cumulative sum of all the integers
> from index zero into another array. So for the array above, I should
> get: [ 0, 1, 3, 4, 5, 5, 5, 7, 10 ]
>   What is the best way (or pythonic way) to get this.

At least for large arrays, this is the kind of task where NumPy will
help.

>>> import numpy as np
>>> np.cumsum([ 0, 1, 2, 1, 1, 0, 0, 2, 3 ])
array([ 0,  1,  3,  4,  5,  5,  5,  7, 10])





More information about the Python-list mailing list