Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何理解python制作列表时的列表理解?_Python_List_List Comprehension - Fatal编程技术网

如何理解python制作列表时的列表理解?

如何理解python制作列表时的列表理解?,python,list,list-comprehension,Python,List,List Comprehension,我有一个元组列表,它将被转换成另一个列表,其中包含列表类型的元素,因为每个元素都是一个列表,我们可以在头部插入自然数。让我们把: l = [('c++', 'compiled'), ('python', 'interpreted')] lx = [] for z in xrange(len(l)): y = [x for x in l[z]] y.insert(0, z) lx.append(y) print lx

我有一个元组列表,它将被转换成另一个列表,其中包含列表类型的元素,因为每个元素都是一个列表,我们可以在头部插入自然数。让我们把:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]]
        y.insert(0, z)
        lx.append(y)
    print lx
    [[0, 'c++', 'compiled'], [1, 'python', 'interpreted']]
看,工作完成了,它是这样工作的。下列情况除外

都不是:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]]
        lx.append(y.insert(0, z))
    print lx
    [None, None]
也不是:

更不用说:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        lx.append([x for x in l[z]].insert(0, z))
    print lx
    [None, None]
有效,为什么?我注意到如下情况:

y = [x for x in l[z]]

在调试中没有一个周期一步一步地执行,这超出了我对其他语言表达式的印象。

insert方法不返回任何内容,在Python中,这相当于返回
None
常量。例如,在这一行之后:

y = [x for x in l[z]].insert(0, z)

y
将始终
None
。这就是你加在lx上的结果。您的第一个片段是正确的方法。这个问题与列表理解无关

insert方法不返回任何内容,在Python中,这相当于返回
None
常量。例如,在这一行之后:

y = [x for x in l[z]].insert(0, z)

y
将始终
None
。这就是你加在lx上的结果。您的第一个片段是正确的方法。这个问题与列表理解无关

>[]插入(0,1)
>
>>
简短版本:
lx=[[i,v[0],v[1]]在枚举(l)]中为i,v插入(0,1)
@Matthias或者-如果假设总是有一个2元组,那么在枚举(l)]
中为i,(a,b)]
将更有效
>>
简短版本:
lx=[[i,v[0],v[1]]表示枚举(l)]
@Matthias或者-如果假设总是有一个2元组,那么
[[i,a,b]表示枚举(l)]
将更有效,而且如果OP真的想使用列表comp,他们可能在
lx=[i]+list(el)之后对于i,el在enumerate(l)]
-而不是doinsert…@JonClements:这就是我要找的语法。谢谢。@JonClements ExcellentAnd是真正想使用列表comp的OP-他们可能在枚举(l)中的
lx=[[i]+list(el)for i,el]
-而且根本不做插入…@JonClements:这就是我要找的语法。谢谢。@JonClements好极了