generate list of partially accumulated values

buffi bjorn.kempen at gmail.com
Sun Sep 16 06:02:59 EDT 2007


On Sep 16, 11:56 am, cesco <fd.calabr... at gmail.com> wrote:
> Hi,
>
> I have the following list:
> l = [1, 2, 3, 4]
> and I'd like to obtain a list like the following:
> l_partial_sum = [1, 3, 6, 10] (that is [1, 1+2, 1+2+3, 1+2+3+4])
>
> Is there a simple way to accomplish this?
>
> I came up with the following solution but it seems a bit too
> elaborated for the task:
> l_partial_sum = [reduce(lambda x,y:x+y, sub_l) for sub_l in [l[:i+1]
> for i in range(len(l))]]
>
> Any help will be appreciated.
>
> Thanks
> Francesco

>>> l = [1, 2, 3, 4]
>>> [sum(l[:x+1]) for x in xrange(len(l))]
[1, 3, 6, 10]

- Björn Kempén




More information about the Python-list mailing list