我尝试在字典上使用嵌套生成器理解,并将列表作为存储值,并观察到以下奇怪的(对我而言)行为:
Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dummy = {1:[1,2,3],2:[2,3,4],3:[3,4,5]}
>>> a = (d for _,d in dummy.iteritems())
>>> a.next()
[1, 2, 3]
>>> a.next()
[2, 3, 4]
>>> a.next()
[3, 4, 5]
>>> a.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
这是有道理的。接下来的事情没有(至少对我而言)
>>> aa = (dd for dd in (d for _,d in dummy.iteritems()))
>>> aa.next()
[1, 2, 3]
>>> aa.next()
[2, 3, 4]
>>> aa.next()
[3, 4, 5]
>>> aa.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
为什么我的(尝试的)嵌套生成器理解的行为方式与非嵌套版本相同?我本来希望每个 aa.next() 给出一个元素结果,而不是一个列表。