【问题标题】:Read flat list into multidimensional array/matrix in python将平面列表读入python中的多维数组/矩阵
【发布时间】:2011-04-07 20:56:02
【问题描述】:

我有一个数字列表,代表另一个程序生成的矩阵或数组的扁平输出,我知道原始数组的维度,并希望将数字读回列表列表或 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]]

提前干杯

【问题讨论】:

    标签: python multidimensional-array numpy


    【解决方案1】:

    使用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 文档中的探索。谢谢
    【解决方案2】:

    如果你不想使用 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)]
    

    【讨论】:

      【解决方案3】:

      对于那里的那些班轮:

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

      【讨论】:

        【解决方案4】:

        如果没有 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))
        

        【讨论】:

          猜你喜欢
          • 2017-04-15
          • 2012-05-24
          • 1970-01-01
          • 2019-04-28
          • 2013-05-17
          • 2012-09-16
          • 2014-05-09
          • 2013-01-22
          • 2016-06-09
          相关资源
          最近更新 更多