我想您可以将上述表达式中的内部循环大致翻译为:
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 不同的对象。由于它是一个单独的对象(与其名称分开存储在当前范围内以允许对其进行迭代),因此在当前范围内将新变量绑定到该名称没有问题——也许我应该说没有问题除了它使代码真的很难遵循。
这实际上与您执行此操作没有问题的原因相同:
A = [['foo']] #Define A
b = A[0] #Take information from A and rebind it to something else
c = A #We can even take the entire reference and bind/alias it to a new name.
A = 'bar' #Re-assign A -- Python doesn't care that A already existed.
这里还有一些需要考虑的事情:
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))