在python中将平面列表读入多维数组/矩阵
我有一个数字列表,它表示另一个程序生成的矩阵或数组的平坦输出,我知道原始数组的维数,我想把数字读回列表或NumPy矩阵。原始数组中可能有两个以上的维度 e、 g 将产生: [[0,2,7,6], [3,1,4,5]] 提前欢呼使用: 如果要避免在内存中复制在python中将平面列表读入多维数组/矩阵,python,multidimensional-array,numpy,Python,Multidimensional Array,Numpy,我有一个数字列表,它表示另一个程序生成的矩阵或数组的平坦输出,我知道原始数组的维数,我想把数字读回列表或NumPy矩阵。原始数组中可能有两个以上的维度 e、 g 将产生: [[0,2,7,6], [3,1,4,5]] 提前欢呼使用: 如果要避免在内存中复制数据的形状属性,也可以直接指定该属性: >>> data.shape = shape 如果您不想使用numpy,2d案例有一个简单的单行线: group = lambda flat, size: [flat[i:i+size
数据
的形状
属性,也可以直接指定该属性:
>>> data.shape = shape
如果您不想使用numpy,2d案例有一个简单的单行线:
group = lambda flat, size: [flat[i:i+size] for i in range(0,len(flat), size)]
可通过添加递归对多维进行推广:
import operator
def shape(flat, dims):
subdims = dims[1:]
subsize = reduce(operator.mul, subdims, 1)
if dims[0]*subsize!=len(flat):
raise ValueError("Size does not match or invalid")
if not subdims:
return flat
return [shape(flat[i:i+subsize], subdims) for i in range(0,len(flat), subsize)]
对于那些一言堂的人:
>>> data = [0, 2, 7, 6, 3, 1, 4, 5]
>>> col = 4 # just grab the number of columns here
>>> [data[i:i+col] for i in range(0, len(data), col)]
[[0, 2, 7, 6],[3, 1, 4, 5]]
>>> # for pretty print, use either np.array or np.asmatrix
>>> np.array([data[i:i+col] for i in range(0, len(data), col)])
array([[0, 2, 7, 6],
[3, 1, 4, 5]])
没有Numpy,我们也可以做如下事情
l1 = [1,2,3,4,5,6,7,8,9]
def convintomatrix(x):
sqrt = int(len(x) ** 0.5)
matrix = []
while x != []:
matrix.append(x[:sqrt])
x = x[sqrt:]
return matrix
print (convintomatrix(l1))
太棒了!真不敢相信我错过了在NumPy docs周围闲逛的机会。谢谢
>>> data = [0, 2, 7, 6, 3, 1, 4, 5]
>>> col = 4 # just grab the number of columns here
>>> [data[i:i+col] for i in range(0, len(data), col)]
[[0, 2, 7, 6],[3, 1, 4, 5]]
>>> # for pretty print, use either np.array or np.asmatrix
>>> np.array([data[i:i+col] for i in range(0, len(data), col)])
array([[0, 2, 7, 6],
[3, 1, 4, 5]])
l1 = [1,2,3,4,5,6,7,8,9]
def convintomatrix(x):
sqrt = int(len(x) ** 0.5)
matrix = []
while x != []:
matrix.append(x[:sqrt])
x = x[sqrt:]
return matrix
print (convintomatrix(l1))