1

我有一个这样的列表: -

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]

谁能解释一下这些是如何给出这样的输出的。这两次迭代有什么不同?

4

2 回答 2

12

在第一个 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
于 2013-09-05T08:19:47.877 回答
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一开始没有定义,循环将不起作用。

于 2013-09-05T08:23:45.250 回答