문제

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