我有一个数字列表,表示另一个程序生成的矩阵或数组的扁平化输出,我知道原始数组的维度,想将这些数字读回到列表列表或 NumPy 矩阵中。原始数组中可能有超过 2 个维度。
例如
data = [0, 2, 7, 6, 3, 1, 4, 5]
shape = (2,4)
print some_func(data, shape)
会产生:
[[0,2,7,6], [3,1,4,5]]
提前干杯
最佳答案
使用numpy.reshape
:
>>> import numpy as np
>>> data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] )
>>> shape = ( 2, 4 )
>>> data.reshape( shape )
array([[0, 2, 7, 6],
[3, 1, 4, 5]])
如果你想避免在内存中复制它,你也可以直接分配给 data
的 shape
属性:
>>> data.shape = shape
关于python - 在python中将平面列表读入多维数组/矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636344/