Python列表理解:展平列表列表将返回5s列表 [英] Python list comprehension: Flattening a list of lists returns a list of 5s

查看:33
本文介绍了Python列表理解:展平列表列表将返回5s列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表列表:

>>>> vec=[[1,2,3],[4,5,6],[7,8,9]]

要使用列表理解来整理列表的列表,我可以使用:

To flatten a list of lists using list comprehension I can use:

>>>>[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是从哪里来的?

so what's happening? where do these 5s come from?

推荐答案

如果您使用的是Python 3,因为该问题已被标记,那么您必须在某个时候将 i 反弹至5.在Python 3中,listcomp具有自己的作用域,因此您显示的命令甚至无法使用:

If you're using Python 3 as this question is tagged, then you must have rebound i to 5 at some point. In Python 3 listcomps have their own scope, and so the commands you've shown won't even work:

>>> 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

因为listcomp没有将 i 设置为任何值,所以它试图从外部范围中获取值,并且(与您不同:-)我没有将其设置为任何值.

Because the listcomp doesn't set i to anything, it's trying to get a value from the outer scope, and (unlike you :-) I haven't set it to anything.

通过对比,在Python 2中, i 将从 [i在vec中用于k在k中用于i在k中] listcomp中泄漏出来,

By way of contrast, in Python 2, i would leak from the [i for k in vec for i in k] listcomp and you'd wind up with

>>> [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]

这篇关于Python列表理解:展平列表列表将返回5s列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆