一. 最直接的方式:用numpy.random模塊來生成隨機數(shù)組
1斋泄、np.random.rand 用于生成[0.0, 1.0)之間的隨機浮點數(shù)署惯, 當沒有參數(shù)時,返回一個隨機浮點數(shù),當有一個參數(shù)時,返回該參數(shù)長度大小的一維隨機浮點數(shù)數(shù)組,參數(shù)建議是整數(shù)型代承,因為未來版本的numpy可能不支持非整形參數(shù)汁蝶。
import numpy as np
>>> np.random.rand(10)
array([ 0.89103033, 0.60550521, 0.13856488, 0.57468244, 0.370697 ,
0.31823162, 0.58358377, 0.97177935, 0.76400592, 0.11269547])
2、np.random.randn該函數(shù)返回一個樣本论悴,具有標準正態(tài)分布掖棉。
>>> np.random.randn(10)
array([-0.42625455, -1.86248727, 0.96323332, -0.32809754, -0.79697695,
-0.07145189, 2.89728643, 2.32095237, 1.12925633, -0.39210317])
3、np.random.randint(low[, high, size]) 返回隨機的整數(shù)膀估,位于半開區(qū)間 [low, high)幔亥。
>>> np.random.randint(10,size=10)
array([4, 1, 4, 3, 8, 2, 8, 5, 8, 9])
4、random_integers(low[, high, size]) 返回隨機的整數(shù)察纯,位于閉區(qū)間 [low, high]帕棉。
>>> np.random.random_integers(5)
2
5、 np.random.shuffle(x) 類似洗牌饼记,打亂順序香伴;np.random.permutation(x)返回一個隨機排列
>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8]
>>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
二. 用random模塊自己構(gòu)造
1、random.randint(low, hight) -> 返回一個位于[low,hight]之間的整數(shù)
該函數(shù)接受兩個參數(shù)具则,這兩個參數(shù)必須是整數(shù)(或者小數(shù)位是0的浮點數(shù))即纲,并且第一個參數(shù)必須不大于第二個參數(shù)
>>> import random
>>> random.randint(1,10)
6
>>> random.randint(1.0, 10.0)
1
2、random.random() -> 不接受參數(shù)博肋,返回一個[0.0, 1.0)之間的浮點數(shù)
>>> random.random()
0.5885821552646049
3低斋、random.uniform(val1, val2) -> 接受兩個數(shù)字參數(shù),返回兩個數(shù)字區(qū)間的一個浮點數(shù)匪凡,不要求val1小于等于val2
>>> random.uniform(1,5.0)
4.485403087612088
>>> random.uniform(9.9, 2)
5.189511116007191
4膊畴、random.randrange(start, stop, step) -> 返回以start開始,stop結(jié)束病游,step為步長的列表中的隨機整數(shù)巴比,同樣,三個參數(shù)均為整數(shù)(或者小數(shù)位為0)礁遵,若start大于stop時 轻绞,setp必須為負數(shù).step不能是0.
>>> random.randrange(1, 100, 2) #返回[1,100]之間的奇數(shù)
19
>>> random.ranrange(100, 1, -2) #返回[100,1]之間的偶數(shù)
2
5、生成隨機數(shù)組
方法佣耐,使用random.ranident,構(gòu)造一個列表即可:
import random
def random_list(start,stop,length):
if length>=0:
length=int(length)
start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
random_list = []
for i in range(length):
random_list.append(random.randint(start, stop))
return random_list