Skip to content Skip to sidebar Skip to footer

Fill A 2d List With Random Numbers In Python

I have created a function to fill a 2D array, but it does not work as intended: from random import * def fill_matrix(maxrow, maxcol): mymatrix = [ [ None ] * maxrow ] * maxcol

Solution 1:

when you do arr= [[None]*2]*3 you create a list with 3 lists referencing to same list. so if one list changes all the other ones will change. So replace mymatrix = [ [ None ] * maxrow ] * maxcol by

mymatrix = [ [ Nonefor i inrange (maxrow) ] for j inrange (maxcol)]

Solution 2:

Try using numpy:

import numpy as np

print(np.random.randint(0,9,size=(4,3)))

Solution 3:

you can try it

import numpy as nplist2D= (np.random.random((N,N))).tolist()

output, when N=5:

[[0.5443335192306711, 0.06610164916627725, 0.9464264551530688, 
0.8714989296172226, 0.343053651834623], [0.4694855513495554, 
0.9109844708363358, 0.9857587537047011, 0.7607561949627727, 
0.46307440609410333], [0.050891396239376996, 0.13672955575820833, 
0.8549886951728779, 0.8803310239366302, 0.04983877880553622], 
[0.3503177755755804, 0.08222507697906556, 0.7144017087408304, 
0.6117493050623465, 0.68059136839199], [0.2244599257314427, 
0.06203059400599176, 0.9342379337438128, 0.5204524652150645, 0.44055560620795253]]

see this link: enter link description here

Post a Comment for "Fill A 2d List With Random Numbers In Python"