質問

It's my understanding that python generator expressions return lazily evaluated comprehensions, and view objects on dictionaries update when their underlying dictionary is changed.

Given the following code (Python 2.7.6 Windows):

d = {}
gt_three = (x for x in d.viewkeys() if x > 3)
print list(gt_three)
d[1] = 'one'
d[4] = 'four'
print list(gt_three)

I would expect output like:

[]
[4]

Instead, I'm receiving:

[]
[]

If I recreate the generator after adding to the dictionary, or print the view itself, I do see the expected output. What am I not understanding about generators? I'm quite new to python.

役に立ちましたか?

解決

A generator expression returns an iterator, which you can only iterate over once. Attempts to iterate over an iterator after the first time will always see it as empty.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top