在python中将平面列表读入多维数组/矩阵

Chr*_*ris 8 python numpy multidimensional-array

我有一个数字列表,表示由另一个程序生成的矩阵或数组的平坦输出,我知道原始数组的尺寸,并希望将数字读回列表列表或NumPy矩阵.原始数组中可能有两个以上的维度.

例如

data = [0, 2, 7, 6, 3, 1, 4, 5]
shape = (2,4)
print some_func(data, shape)
Run Code Online (Sandbox Code Playgroud)

会产生:

[[0,2,7,6],[3,1,4,5]]

提前干杯

Kat*_*iel 21

用途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]])
Run Code Online (Sandbox Code Playgroud)

如果要避免在内存中复制它,也可以直接指定shape属性data:

>>> data.shape = shape
Run Code Online (Sandbox Code Playgroud)


Vaj*_*ecz 5

如果您不想使用numpy,那么对于2d情况,有一个简单的oneliner:

group = lambda flat, size: [flat[i:i+size] for i in range(0,len(flat), size)]
Run Code Online (Sandbox Code Playgroud)

可以通过添加递归来将其概括为多维:

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)]
Run Code Online (Sandbox Code Playgroud)


B.M*_*.W. 5

对于那些那里的衬里:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)