在第一个 LC 结束时,i
分配给[8,9]
:
>>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
>>> [j for i in lis for j in i]
[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
>>> i
[8, 9]
现在在第二个 LC 中,您正在迭代这个i
:
>>> [j for j in i for i in lis]
[8, 8, 8, 8, 9, 9, 9, 9]
两个 LC 都(大致)等同于:
>>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
>>> for i in lis:
... for j in i:
... print j,
...
1 2 3 4 5 6 4 5 6 7 8 9
>>> i
[8, 9]
>>> for j in i:
... for i in lis:
... print j,
...
8 8 8 8 9 9 9 9
这已在 py3.x 中修复:
特别是循环控制变量不再泄漏到周围的范围内。
演示(py 3.x):
>>> lis = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
>>> [j for i in lis for j in i]
[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
>>> i
Traceback (most recent call last):
NameError: name 'i' is not defined
>>> j
Traceback (most recent call last):
NameError: name 'j' is not defined