Read flat list into multidimensional array/matrix in python

后端 未结 4 655
说谎
说谎 2020-12-05 21:25

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 t

4条回答
  •  余生分开走
    2020-12-05 21:36

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

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

提交回复
热议问题