Simple way to create matrix of random numbers

前端 未结 13 1675
灰色年华
灰色年华 2020-12-12 21:20

I am trying to create a matrix of random numbers, but my solution is too long and looks ugly

random_matrix = [[random.random() for e in range(2)] for e in ra         


        
13条回答
  •  不思量自难忘°
    2020-12-12 22:01

    #this is a function for a square matrix so on the while loop rows does not have to be less than cols.
    #you can make your own condition. But if you want your a square matrix, use this code.
    
    import random
    
    import numpy as np
    
    def random_matrix(R, cols):
    
            matrix = []
    
            rows =  0
    
            while  rows < cols:
    
                N = random.sample(R, cols)
    
                matrix.append(N)
    
                rows = rows + 1
    
        return np.array(matrix)
    
    print(random_matrix(range(10), 5))
    #make sure you understand the function random.sample
    

提交回复
热议问题