连接数组Matrix沿指定的维度。蟒蛇

时间:2016-12-13 09:32:06

标签: python arrays matrix

如何以不同维度连接C1和C2?

C1 =[[0,0,1,0],
    [2,0,0,0],
    [0,0,0,0]]

C2=[[0,3,4,0,1,1],
    [0,0,0,5,1,1],
    [6,7,0,8,1,1]]

如何获得以下结果:

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

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

2 个答案:

答案 0 :(得分:1)

>>> [r1+r2 for (r1, r2) in zip(C1, C2)]
[[0, 0, 1, 0, 0, 3, 4, 0, 1, 1], [2, 0, 0, 0, 0, 0, 0, 5, 1, 1], [0, 0, 0, 0, 6, 7, 0, 8, 1, 1]]

>>> C1 + C2
[[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 3, 4, 0, 1, 1], [0, 0, 0, 5, 1, 1], [6, 7, 0, 8, 1, 1]]

答案 1 :(得分:0)

使用列表理解 -

>>> [i[0]+i[1] for i in zip(C1, C2)]
[[0, 0, 1, 0, 0, 3, 4, 0, 1, 1], [2, 0, 0, 0, 0, 0, 0, 5, 1, 1], [0, 0, 0, 0, 6, 7, 0, 8, 1, 1]]

>>> C1 + C2
[[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 3, 4, 0, 1, 1], [0, 0, 0, 5, 1, 1], [6, 7, 0, 8, 1, 1]]