【问题标题】:How to append i'th element of a list to first entry in i'th list in list of lists?如何将列表的第 i 个元素附加到列表列表中第 i 个列表的第一个条目?
【发布时间】:2021-08-22 07:59:14
【问题描述】:

即:列表中的每个元素最终都作为列表列表中相应列表中的第一个元素。

如下:

List_of_Lists = [[1,2,3],[2,3,4],[4,4,4]]
List1 = [1,2,3]

结果:

New_List_of_List = [[1,1,2,3][2,2,3,4],[3,4,4,4]]

我尝试了各种追加和插入方法,但主要问题是我不确定如何将 List_of_Lists 中的单个列表和 List 中的元素混合在一起。

【问题讨论】:

  • 你形成的问题90%是答案本身。只是word格式的

标签: python list append


【解决方案1】:

可以在0位置插入元素

lists = [[1,2,3],[2,3,4],[4,4,4]]
List1 = [1,2,3]
for i in range(len(lists)):
    
     lists[i].insert(0,List1[i])
print(lists)

输出:

[[1, 1, 2, 3], [2, 2, 3, 4], [3, 4, 4, 4]]

【讨论】:

    【解决方案2】:

    另一种解决方案:

    List_of_Lists = [[1, 2, 3], [2, 3, 4], [4, 4, 4]]
    List1 = [1, 2, 3]
    
    out = [[v, *subl] for v, subl in zip(List1, List_of_Lists)]
    print(out)
    

    打印:

    [[1, 1, 2, 3], [2, 2, 3, 4], [3, 4, 4, 4]]
    

    【讨论】:

      【解决方案3】:

      试试这个:

      for idx, sub_list in enumerate(List_of_Lists):
          sub_list.insert(0, List1[idx])
      

      上面的代码会修改你的 List_of_Lists,如果你不想这样,请创建一个副本,然后循环遍历该副本。

      【讨论】:

        【解决方案4】:

        这是我编写的示例代码,用于在子列表的任意位置插入值。

        import copy
        List_of_Lists = [[1,2,3],[2,3,4],[4,4,4]]
        List1 = ['Z','Y','X']
        
        def Insert_List_of_Lists(List_X,index,value):
            temp_list=copy.deepcopy(List_X)
            if index<=len(temp_list):
               for i in range(len(temp_list)):
                   temp_list[i].insert(index,value)
            else:
               for i in range(len(temp_list)):
                   temp_list[i].insert(len(temp_list),value)
               print("Given index Out of range, value appended")
            return(temp_list)
        
        New_List_of_List = Insert_List_of_Lists(List_of_Lists,3,List1[0])
        New_List_of_List
        

        输出:

        [[1, 2, 3, 'Z'], [2, 3, 4, 'Z'], [4, 4, 4, 'Z']]
        

        当我们尝试从索引中添加一个值时:

        X_list = Insert_List_of_Lists(List_of_Lists,8,'J')
        X_list
        

        输出:

        Given index Out of range, value appended
        [[1, 2, 3, 'J'], [2, 3, 4, 'J'], [4, 4, 4, 'J']]
        

        【讨论】:

          猜你喜欢
          • 2016-08-03
          • 2019-04-16
          • 2020-09-20
          • 2021-10-17
          • 1970-01-01
          • 1970-01-01
          • 2021-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多