【问题标题】:Append list elements to list of lists in python将列表元素附加到python中的列表列表
【发布时间】:2017-12-18 07:37:39
【问题描述】:

鉴于以下列表:

list1 = [[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]]
list2 = [10, 11, 12, 13]

更改list1 使其成为python 中的以下列表的最佳方法是什么?

[[1, 2, 10],
 [3, 4, 11],
 [5, 6, 12],
 [7, 8, 13]]

【问题讨论】:

    标签: python list python-3.x append


    【解决方案1】:

    你可以这样做:

    list1 = [[1, 2],
             [3, 4],
             [5, 6],
             [7, 8]]
    list2 = [10, 11, 12, 13]
    
    def add_item_to_list_of_lists(list11, list2):
        # list1, list to add item of the second list to
        # list2, list with items to add to the first one
        for numlist, each_list in enumerate(list1):
            each_list.append(list2[numlist])
    
    add_item_to_list_of_lists(list1, list2)
    print(list1)
    

    输出

    [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
    

    【讨论】:

    • 为什么要提供mutable default args?他们的内容应该是 cmets 吗?
    • 你为什么用list1[numlist]而不是each_list
    【解决方案2】:

    或者,如果您使用的是 Python >= 3.5,则在 ziping 之后进行解包理解:

    >>> l = [[*i, j] for i,j in zip(list1, list2)]
    >>> print(l)
    [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
    

    当然,如果列表大小可能不同,您最好使用zip_longest from itertools 来优雅地处理额外的元素。

    【讨论】:

      【解决方案3】:

      你可以使用zip:

      [x + [y] for x, y in zip(list1, list2)]
      # [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
      

      要修改list1,您可以:

      for x, y in zip(list1, list2):
          x.append(y)
      
      list1
      # [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-17
        • 2020-10-29
        • 2020-09-02
        • 2023-03-09
        • 2015-02-05
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多