如何将列表列表合并为一个?

时间:2017-10-08 00:31:55

标签: python list

如果我有2个列表清单:

A = [ [[2,3],[3,4]] ] 

B = [ [[5,6],[7,3],[3,1]],
      [[2,5],[3,2],[4,2]],
      [[2,1],[2,3],[3,1]] ] 

我希望将A合并到B.所以A的列表的第一个列表在B的第一个列表中,依此类推。

输出:

 C = [ [[5,6],[7,3],[3,1],[2,3],[3,4]],
       [[2,5],[3,2],[4,2]],
       [[2,1],[2,3],[3,1]] ]  

我尝试使用zip(A,B),但是它们被放在元组和列表中,所以它真的很混乱?

4 个答案:

答案 0 :(得分:0)

这样可行:

>>> A=[ [ [2,3],[3,4] ] ]
>>> B=[ [ [ [5,6],[7,3],[3,1]],[ [2,5],[3,2],[4,2] ],[ [2,1],[2,3],[3,1]]]]
>>> B[0][0] += A[0]
>>> B
[[[[5, 6], [7, 3], [3, 1], [2, 3], [3, 4]], [[2, 5], [3, 2], [4, 2]], [[2, 1], [2, 3], [3, 1]]]]

编辑回答。

答案 1 :(得分:0)

它不是一个oneliner但它解决了你的问题:

def my_list_merge(A,B):
    """ Merge the elements from A into B """
    C = []
    for i in range(len(A)):
        C += [B[i]+A[i]]
    C += B[i+1:]
    return C

所以在一些更容易阅读的数据上使用这个方法:

>>> A = [ [[4,4]] ]
>>> B = [ [[1,1],[1,1]],
          [[2,2],[2,2]],
          [[3,3],[3,3]] ]
>>> my_list_merge(A,B)
 [ [[1, 1], [1, 1], [4, 4]],
   [[2, 2], [2, 2]],
   [[3, 3], [3, 3]] ]

并显示它的尺度(s.t. len(A)< = len(B))

>>> A = [ [[4,4],[4,4]] ]
>>> B = [ [[1,1],[1,1],[1,1]], 
          [[2,2],[2,2],[2,2]], 
          [[3,3],[3,3],[3,3]] ]
>>> my_list_merge(A,B)
[[[1, 1], [1, 1], [1, 1], [4, 4], [4, 4]],
 [[2, 2], [2, 2], [2, 2], [5, 5], [5, 5]],
 [[3, 3], [3, 3], [3, 3]]]

答案 2 :(得分:0)

这应该适合你。

A = [ [ [2,3],[3,4] ] ]

B = [ [ [5,6],[7,3],[3,1]],[ [2,5],[3,2],[4,2] ],[ [2,1],[2,3],[3,1]]]

C = [B[0] + A[0], B[1], B[2]]

print(C)

打印:

[[[5, 6], [7, 3], [3, 1], [2, 3], [3, 4]], [[2, 5], [3, 2], [4, 2]], [[2, 1], [2, 3], [3, 1]]]

答案 3 :(得分:0)

尝试使用A.append(B),它会为您添加列表。