Is there a list comprehension for this?
Mathias Panzenboeck
e0427417 at student.tuwien.ac.at
Tue Nov 21 16:58:22 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.
>
Is this a function where you just want to know a w[n]?
then:
def w(n):
return sum((1 + i * 0.1) * (i % 2 and 1 or -1) for i in xrange(n))
otherwise:
n, w, x = 3, [], 0
for y in ((1 + i * 0.1) * (i % 2 and 1 or -1) for i in xrange(n)):
x += y
w.append(x)
More information about the Python-list
mailing list