Is there a list comprehension for this?

Peter Otten __peter__ at web.de
Wed Nov 22 02:54:10 EST 2006


liam_herron wrote:

> 
> Given:
> dw = [ 1, -1.1, +1.2 ]
> 
> Suppose I want to create a list 'w' that is defined as
> 
> w[0] = dw[0],
> w[1] = w[0] + dw[1],
> w[2] = w[1] + dw[2]
> 
> Is there a list comprehension or map expression to do it in one or 2
> lines.

>>> from itertools import *
>>> data = [1, -1.1, 1.2]
>>> N = 2
>>> [sum(item) for item in izip(*[chain(repeat(0, i), di) for i, di in
enumerate(tee(data, N))])]
[1, -0.10000000000000009, 0.099999999999999867]

Should work for other values of N, too. No, I'm not serious about it...

Peter



More information about the Python-list mailing list