Is there a list comprehension for this?

Tim Chase python.list at tim.thechases.com
Tue Nov 21 16:45:42 EST 2006


> 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.

Well, while it's not terribly efficient, you can do something like

	w = [sum(dw[:i]) for i in xrange(1,len(dw)+1)]

Or, if you need the efficiencies for larger len(dw) values, you 
could do something like

 >>> def f(x):
...     i = 0
...     for item in x:
...             i += item
...             yield i
...
 >>> list(i for i in f(dw))
[1, -0.10000000000000009, 1.0999999999999999]

Just a few ideas,

-tkc






More information about the Python-list mailing list