将平面列表读入Python多维数组/矩阵

11 投票
5 回答
61957 浏览
提问于 2025-04-16 03:40

我有一串数字,这些数字是由另一个程序生成的一个矩阵或数组的扁平化输出。我知道原始数组的尺寸,想把这些数字重新读回成一个列表的列表,或者一个NumPy矩阵。原始数组可能有超过两个维度。

比如:

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 个回答

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

撰写回答