将向量转换成MxN矩阵

时间:2019-05-20 10:49:29

标签: python

如何将向量转换为MxN矩阵? 我已经尝试过重塑,但无法弄清楚。

a vector A 
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
b = 3
C = 5

New matrix 
M = [[1,2,3,4,5],
     [6,7,8,9,10],
     [11,12,13,14,15]]

2 个答案:

答案 0 :(得分:0)

尝试使用numpy:

import numpy as np 

A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
b = 3
C = 5

x = np.reshape(A, (b, C))

print(x)

答案 1 :(得分:0)

A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
C = 5

M = [A[i:i + C] for i in range(0, len(A), C)]
print (M)

输出:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]