Read flat list into multidimensional array/matrix in python

后端 未结 4 637
说谎
说谎 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:31

    Without Numpy we can do as below as well..

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

提交回复
热议问题