Accumulate function in python
Joel Goldstick
joel.goldstick at columbuswebmakers.com
Mon Jul 19 18:08:25 EDT 2010
Peter Otten wrote:
> dhruvbird wrote:
>
>> 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.
>
> Homework?
>
>>>> def cumulative_sum(values, start=0):
> ... for v in values:
> ... start += v
> ... yield start
> ...
>>>> list(cumulative_sum([ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]))
> [0, 1, 3, 4, 5, 5, 5, 7, 10]
>
> Peter
nice! Peter
More information about the Python-list
mailing list