2010-09-03 174 views
6

我有一個數字列表,表示由另一個程序產生的矩陣或數組的平坦輸出,我知道原始數組的維度,並且想要將數字讀回到列表或NumPy矩陣列表。原始數組中可能有2個以上的維度。將扁平列表讀入python中的多維數組/矩陣

例如

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]

歡呼提前

回答

15

使用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]]) 

您也可以直接指定shape attrib的data如果你想UTE避免內存複製它:

>>> data.shape = shape 
+0

盛大!我不敢相信我錯過了NumPy文檔。謝謝 – Chris 2010-09-03 14:02:59

3

如果你不想使用numpy的,對於2D情況簡單oneliner:

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)] 
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]])