【问题标题】:Python: Inserting a list of lists into another list of lists [duplicate]Python:将列表列表插入另一个列表列表[重复]
【发布时间】:2013-04-18 14:04:13
【问题描述】:

我想要以下列表:

matrix1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]

matrix2 = [
[A, B, C, D],
[E, F, G, H]
]

并将它们组合成:

new_matrix = [
[A, B, C, D],
[E, F, G, H],
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]

而且我似乎想不出一个好的方法。 Insert() 将整个列表放入其中,从而生成列表列表的列表。任何建议将不胜感激!

【问题讨论】:

    标签: python list


    【解决方案1】:

    只需添加它们!

    new_matrix = matrix1 + matrix2
    

    【讨论】:

    • 好吧,我不觉得自己很愚蠢。谢谢:)
    【解决方案2】:

    使用extend 它用另一个扩展列表而不是将其插入其中。

    >>> matrix2.extend(matrix1)
    

    但是,这将进行适当的更改,而不是创建一个新列表,这可能是您想要的。如果您想创建一个新的,那么+ 就是您所需要的。

    【讨论】:

    • +1,值得注意的是,虽然这是正确的,但 OP 显示了一个保存值的新变量,而这会就地修改列表。这显然取决于想要哪个。
    • @Lattyware 感谢您注意到这一点。我已经更新了答案以明确这一点。
    【解决方案3】:

    使用+ 添加它们:

    In [59]: new_matrix = matrix2 + matrix1
    
    In [60]: new_matrix
    Out[60]: 
    [['A', 'B', 'C', 'D'],
     ['E', 'F', 'G', 'H'],
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12]]
    

    【讨论】:

      【解决方案4】:

      只需使用+ 运算符

      >>> a = [[1],[2],[3]]
      >>> b = [[4],[5],[6]]
      >>> a+b
      [[1], [2], [3], [4], [5], [6]]
      >>> 
      

      【讨论】:

        【解决方案5】:

        许多列表的通用解决方案:

        要么:

        new_matrix = list(itertools.chain(matrix1, matrix2, matrix3, ...)
        

        或者:

        new_matrix = sum(matrix1, matrix2, matrix3, ..., default=[])
        

        或者使用列表列表:

        new_matrix = list(itertools.chain(*matrices)
        

        或者:

        new_matrix = sum(*matrices, default=[])
        

        【讨论】:

        • @Lattyware:如果想要 list 作为最终结果,请指定其中的哪一部分建议反对此操作? OP 不是要求可迭代的,是吗?
        • @Lattyware: 你更喜欢list(itertools.chain(*matrices)) 吗?
        • 是的,列表和其他列表一样是可迭代的,itertools.chain() 是更好的解决方案。至于列出一个列表,正如您所说,转换为列表很容易 - 如果有必要的话。
        • @Lattyware:我重复这个问题,如果你想列出一个列表,它在哪里说itertools.chain 比sum 更推荐?暗示前者是错的……
        猜你喜欢
        • 2011-03-04
        • 2022-12-24
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 2021-07-29
        • 2017-11-02
        • 1970-01-01
        相关资源
        最近更新 更多