我遇到了python的一些问题。
A= [ [1,2,3]
[4,5,6]
]
B = [ [10,11]
[12,13]
]
我希望:
C = [A B]
= [ [1,2,3, 10, 11]
[4,5,6, 12, 13]
]
我如何在python中执行此操作?
答案 0 :(得分:8)
答案 1 :(得分:4)
另外,将np.concatenate
与axis=1
In [207]: np.concatenate((A, B), axis=1)
Out[207]:
array([[ 1, 2, 3, 10, 11],
[ 4, 5, 6, 12, 13]])
如果你关心表演,np.concatenate
就是真正的战马。
In [215]: %timeit np.concatenate((A, B), 1)
The slowest run took 12.10 times longer than the fastest.
100000 loops, best of 3: 3.1 µs per loop
In [214]: %timeit np.hstack((A,B))
The slowest run took 6.85 times longer than the fastest.
100000 loops, best of 3: 12.5 µs per loop
In [216]: %timeit np.c_[A, B]
10000 loops, best of 3: 48.7 µs per loop
答案 2 :(得分:2)
你可以这样做,基本上在压缩(A,B)对象中添加每个列表:
>>> [x + y for x, y in zip(A, B)]
[[1, 2, 3, 10, 11], [4, 5, 6, 12, 13]]
答案 3 :(得分:1)
无法判断您是否询问numpy数组(根据您的标记)或列表列表(每个标题的矩阵)......但是:
连接列表,只需将它们添加到一起:
A = [[1,2,3],[4,5,6]]
B = [[10,11],[12,13]]
C = [A[0]+B[0],A[1]+B[1]]
print C
>>>
[[1, 2, 3, 10, 11], [4, 5, 6, 12, 13]]
如果你有数组开始,你可以使用append方法:
import numpy as np
A = np.array([[1,2,3],[4,5,6]])
B = np.array([[10,11],[12,13]])
C = np.array([np.append(A[0],B[0]),np.append(A[1],B[1])])
print C
>>>
[[ 1 2 3 10 11]
[ 4 5 6 12 13]]