我有一个列表如下: -
lst = [[1, 2, 3, 4, 5, 6], [4, 5, 6], [7], [8, 9]]
如果我运行这些,我得到的输出就像这些。我不知道它们是如何工作的。
>>>[j for i in lst for j in i]
[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
>>>[j for j in i for i in lst]
[8, 8, 8, 8, 9, 9, 9, 9]
任何人都可以解释一下这些输出是如何产生的。这两次迭代之间有什么不同?
答案 0 :(得分:12)
在第一次结束时,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
特别是循环控制变量不再泄漏到 周围范围。
演示(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
答案 1 :(得分:1)
[j for i in list for j in i]
这类似于
result = []
for i in list:
for j in i:
result.append(j)
通常,[p for a in b if c == d for e in f if etc]
等列表理解将被翻译为
reuslt = []
for a in b: if c == d: for e in f: if etc: result.append(p)
[j for j in i for i in list]
通常这甚至不会运行。可能您之前已将i
定义为[8, 9]
。
>>> [j for j in i for i in list]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
这相当于
result = []
for j in i:
for i in list:
result.append(j)
所以如果首先没有定义i
,那么循环将不起作用。