I have a dictionary and as I am creating it during list comprehension can I access the previous values created?
Example:
h = {i:1+h[i-1] for i in range(1,100))}
I have a dictionary and as I am creating it during list comprehension can I access the previous values created?
Example:
h = {i:1+h[i-1] for i in range(1,100))}
Edit: I read i:i + h[i-1]
instead of i:1 + h[i-1]
. The latter is always equal to i:i
except in the first case, when it is 1+None
This does what you want in a dictionary comprehension. Requires Python 3.2 or higher:
from itertools import accumulate
h = {i:v for i,v in enumerate(accumulate(range(100)))}
otherwise use this
def accumulate(r):
next_value = 0
for i in r:
next_value = next_value + i
yield next_value