Simple way of creating a 2D array with random numbers (Python) -
i know easy way create nxn array full of zeroes in python with:
[[0]*n x in range(n)]
however, let's suppose want create array filling random numbers:
[[random.random()]*n x in range(n)]
this doesn't work because each random number created replicated n times, array doesn't have nxn unique random numbers.
is there way of doing in single line, without using loops?
you use nested list comprehension:
>>> n = 5 >>> import random >>> [[random.random() in range(n)] j in range(n)] [[0.9520388778975947, 0.29456222450756675, 0.33025941906885714, 0.6154639550493386, 0.11409250305307261], [0.6149070141685593, 0.3579148659939374, 0.031188652624532298, 0.4607597656919963, 0.2523207155544883], [0.6372935479559158, 0.32063181293207754, 0.700897108426278, 0.822287873035571, 0.7721460935656276], [0.31035121801363097, 0.2691153671697625, 0.1185063432179293, 0.14822226436085928, 0.5490604341460457], [0.9650509333411779, 0.7795665950184245, 0.5778752066273084, 0.3868760955504583, 0.5364495147637446]]
or use numpy
(non-stdlib popular):
>>> import numpy np >>> np.random.random((n,n)) array([[ 0.26045197, 0.66184973, 0.79957904, 0.82613958, 0.39644677], [ 0.09284838, 0.59098542, 0.13045167, 0.06170584, 0.01265676], [ 0.16456109, 0.87820099, 0.79891448, 0.02966868, 0.27810629], [ 0.03037986, 0.31481138, 0.06477025, 0.37205248, 0.59648463], [ 0.08084797, 0.10305354, 0.72488268, 0.30258304, 0.230913 ]])
(p.s. it's idea in habit of saying list
when mean list
, reserving array
numpy ndarray
s. there's built-in array
module own array
type, confuses things more, it's relatively seldom used.)
Comments
Post a Comment