让
X = [[2,3, 5, 6],
[4,5, 9, 10],
[6,1, 3, 9],
[3,7, 11, 12]]
如何输出子矩阵,使得X = [[A,B],[C,D]]?
A = [[2, 3],
[4,5]]
B = [[5,6],
[9, 10]]
C = [[6, 1],
[3,7]]
D = [[3,9],
[11, 12]]
答案 0 :(得分:2)
没有numpy,你可以这样做....
X = [[2,3, 5, 6],
[4,5, 9, 10],
[6,1, 3, 9],
[3,7, 11, 12]]
for i in X:
print([i[ :len(i)//2],i[len(i)//2:]])
答案 1 :(得分:2)
你可以试试这个,假设X总是一个4X4矩阵:
X = [[2,3, 5, 6],
[4,5, 9, 10],
[6,1, 3, 9],
[3,7, 11, 12]]
new_matrix = [[X[i][:2], X[i+1][:2]] for i in range(0, len(X), 2)]
new_matrix.extend([[X[i][2:], X[i+1][2:]] for i in range(0, len(X), 2)])
print(new_matrix)
答案 2 :(得分:2)
使用Numpy的解决方案如下所示:
A = X[0:2, 0:2]
B = X[0:2, 2:4]
C = X[2:4, 0:2]
D = X[2:4, 2:4]
答案 3 :(得分:1)
对于第一个子矩阵,您可以使用
A = [row[:2] for row in X[:2]]
(和其他人一样)
答案 4 :(得分:1)
这是一个不使用numpy的解决方案。
A = [X[i][:2] for i in range(2)]
B = [X[i][2:] for i in range(2)]
C = [X[i][:2] for i in range(2,4)]
D = [X[i][2:] for i in range(2,4)]
>>> A
[[2, 3], [4, 5]]
>>> B
[[5, 6], [9, 10]]
>>> C
[[6, 1], [3, 7]]
>>> D
[[3, 9], [11, 12]]
答案 5 :(得分:1)
一个班轮版本,虽然它的可读性稍差
{{1}}