我想你可以将上面表达式中的内部循环大致翻译为:for e in x:
ee = iter(e)
try:
e = next(ee)
while True
print e
e = next(ee)
except StopIteration
pass
注意,这里的关键在于语句:for e in ...,...通过iterator protocol转换为迭代器。您实际迭代的对象是一个独立的对象,与您最初给它的e不同。因为它是一个单独的对象(在当前作用域中与它的名称分开存储以允许它被迭代),所以在当前作用域中将一个新变量绑定到该名称是没有问题的——也许我应该说除了它使代码很难理解外,没有其他问题。在
实际上,这和你做这件事没有问题的原因是一样的:
^{pr2}$
这里还有几个问题需要考虑:x = [1,2,3,4]
for a in x:
print a
next(a) #Raises an error because lists aren't iterators!
现在是一个很少使用(但有时是必要的)成语:x = [1,2,3,4]
y = iter(x) #create an iterator from the list x
for a in y:
print a
#This next line is OK.
#We also consume the next value in the loop since `iter(y)` returns `y`!
#In fact, This is the easiest way to get a handle on the object you're
#actually iterating over.
next(y)
最后:x = [1,2,3,4]
y = iter(x) #create an iterator from the list x
for a in y:
print a
#This effectively does nothing to your loop because you're rebinding
#a local variable -- You're not actually changing the iterator you're
#iterating over, just as `A = 'bar'` doesn't change the value of
#the variable `c` in one of the previous examples.
y = iter(range(10))