I am new to Python but I have a decent amount of experience in Java and C, I am trying to create an array of a certain size then fill it with random numbers but no python tutorials about arrays mention methods about doing this (if I search explicitly about wanting that I get results that is not the problem) so I was wondering if that is considered a bad practice in Python and there are alternative ways to accomplishing what I want. Thank you.
Still to new to comment on @icejoywoo post ^
list are basically arrays for most purposes.
list comprehension is the easiest way to fill an array with lots of things
[ returnVal for i in range(10)]
any for loop or iterator will work return value itself can be a function
x= [None for i in range(10)]
[None,None..None]
x= [x**2 for i in range(10)]
[0,1,4..81]
y = lambda a: int((a**.5)*100)
x= [y(i) for i in range(10)]
[0, 100, 141, 173, 200, 223, 244, 264, 282, 300]
use random or numpy
In [1]: import random
In [2]: [random.random() for i in range(10)]
Out[2]:
[0.8233249954348517,
0.6215056571076538,
0.6273288221606772,
0.12055176228045617,
0.22782244162965615,
0.9016145766629989,
0.04615407289582629,
0.8870216740449745,
0.5622680783939463,
0.9288600326401598]
In [3]: import numpy
In [4]: numpy.random.rand(5)
Out[4]: array([0.9288893 , 0.66600315, 0.82989425, 0.15717061, 0.33444802])
In [5]: list(numpy.random.rand(5))
Out[5]:
[0.46571036413626277,
0.8268980751228664,
0.9216520894106733,
0.26706936577849916,
0.47348417257319697]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With