我有一个数字列表,表示由另一个程序生成的矩阵或数组的平坦输出,我知道原始数组的尺寸,并希望将数字读回列表列表或NumPy矩阵。原始数组中可能有两个以上的维度。
e.g。
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]]
提前干杯
答案 0 :(得分:19)
>>> 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]])
如果您想避免在内存中复制它,也可以直接指定shape
data
属性:
>>> data.shape = shape
答案 1 :(得分:5)
如果你不想使用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)]
答案 2 :(得分:0)
那些衬里的衬里:
>>> 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]])
答案 3 :(得分:0)
如果没有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))