在Python中将扁平列表读入多维数组/矩阵

11
我有一组数字,它们表示由另一个程序生成的矩阵或数组的扁平输出。我知道原始数组的尺寸,并希望将这些数字读回到一个列表或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]]

提前致谢

5个回答

26

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

如果你想避免复制数据到内存中,你也可以直接将datashape属性赋值:

>>> data.shape = shape

太好了!没想到在 NumPy 文档中瞎逛时错过了那个。谢谢。 - Chris

6
如果您不想使用numpy,在二维情况下有一个简单的一行代码解决方案:
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)]

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

0
[list(x) for x in zip(*[iter(data)]*shape[1])]


(在搜索如何工作时找到了此帖子


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接