我有以下列表清单:
>>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
要使用列表理解来展平列表列表,我可以使用:
>>>>[i for k in vec for i in k]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
但如果我写:
>>>> [i for k in vec]
[5,5,5]
>>>> [i for k in vec for k in k]
[5, 5, 5, 5, 5, 5, 5, 5, 5]
甚至更改vec=[[2,89,6],[34,7,10],[812,55,7],[76765,34,99]]
>>>> [i for k in vec]
[5,5,5,5]
>>>> [i for k in vec for k in k]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
那么发生了什么?这些5来自哪里?
答案 0 :(得分:2)
如果您正在使用Python 3,因为此问题已被标记,那么您必须在某个时候将>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> [i for k in vec for i in k]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> [i for k in vec]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'i' is not defined
反弹到5。在Python 3中,listcomps有自己的范围,所以你所显示的命令甚至无法工作:
i
因为listcomp没有将i
设置为任何内容,它会尝试从外部范围获取值,并且(与您不同:-)我还没有设置它任何事情。
相比之下,在Python 2中,[i for k in vec for i in k]
会从>>> [i for k in vec]
[9, 9, 9]
>>> [i for k in vec for k in k]
[9, 9, 9, 9, 9, 9, 9, 9, 9]
listcomp泄漏而你最终会被
V2