如何理解在python中制作列表中的列表推导?

wor*_*cle 0 python list-comprehension list

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

    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']]
Run Code Online (Sandbox Code Playgroud)

看,完成工作,它以这种方式工作.除以下任何一项外

无论是:

    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]
Run Code Online (Sandbox Code Playgroud)

也不:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]].insert(0, z)
        lx.append(y)
    print lx
    [None, None]
Run Code Online (Sandbox Code Playgroud)

更何况:

    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]
Run Code Online (Sandbox Code Playgroud)

工作,为什么?我注意到如下:

y = [x for x in l[z]]
Run Code Online (Sandbox Code Playgroud)

在逐步调试中没有一个循环执行,这超出了我对其他语言表达的印象.

Bar*_*zKP 5

insert方法不返回任何内容,在Python中等效于返回None常量.所以,例如在这一行之后:

y = [x for x in l[z]].insert(0, z)
Run Code Online (Sandbox Code Playgroud)

y永远None.这就是你追加的lx,因此结果.你的第一个片段是正确的方法.这个问题与列表推导无关.

  • OP是否真的想要使用list-comp - 它们可能是在lx = [[i] + list(el)for i,el in enumerate(l)]` - 并且根本不进行插入. .. (3认同)