[Tutor] list comprehension problem

Dinesh B Vadhia dineshbvadhia at hotmail.com
Fri Jul 3 21:09:08 CEST 2009


I'm suffering from brain failure (or most likely just being brain less!) and need help to create a list comprehension for this problem:

d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1]

Want to create a new list that adds the current number and the prior number, where the prior number is the accumulation of the previous numbers ie.

dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96]

A brute force solution which works is:

>>> dd = []
>>> y = d[0]
>>> for i, x in enumerate(d):
>>>        y += x
>>>        dd.append(y)

Is there a list comprehension solution?

Dinesh

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090703/647b1531/attachment.htm>


More information about the Tutor mailing list