Dinesh B Vadhia wrote:
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?

Python has a reduce function that applies an operator (such as +) to successive elements of an iterable giving a single value (in your case that is 96).

APL has both reduce and scan, where scan gives you exactly what you want. WIBNI Python had scan?


--
Bob Gailer
Chapel Hill NC
919-636-4239
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to