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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3636344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:01:29  来源:igfitidea点击:

Read flat list into multidimensional array/matrix in python

pythonmultidimensional-arraynumpy

提问by Chris

I have a list of numbers that represent the flattened output of a matrix or array produced by another program, I know the dimensions of the original array and want to read the numbers back into either a list of lists or a NumPy matrix. There could be more than 2 dimensions in the original array.

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

e.g.

例如

data = [0, 2, 7, 6, 3, 1, 4, 5]
shape = (2,4)
print some_func(data, shape)

Would produce:

会产生:

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

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

Cheers in advance

提前干杯

采纳答案by Katriel

Use numpy.reshape:

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

You can also assign directly to the shapeattribute of dataif you want to avoid copying it in memory:

如果你想避免在内存中复制它,你也可以直接分配给shape属性data

>>> data.shape = shape

回答by Vajk Hermecz

If you dont want to use numpy, there is a simple oneliner for the 2d case:

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

group = lambda flat, size: [flat[i:i+size] for i in range(0,len(flat), size)]

And can be generalized for multidimensions by adding recursion:

并且可以通过添加递归来推广多维:

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

回答by B.Mr.W.

For those one liners out there:

对于那里的那些班轮:

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