简体   繁体   中英

In python list comprehension can we look at previous values created during execution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM