使用random模塊生成隨機數(shù)組
python的random模塊中有一些生成隨機數(shù)字的方法,例如random.randint,random.random,random.uniform,random.randrange,這些函數(shù)大同小異,均是在返回指定范圍內(nèi)的一個整數(shù)或浮點數(shù),下邊簡單解釋一下這幾個函數(shù)。
1、random.randint(low,hight)->返回一個位于[low,hight]之間的整數(shù)
該函數(shù)接受兩個參數(shù),這兩個參數(shù)必須是整數(shù)(或者小數(shù)位是0的浮點數(shù)),并且第一個參數(shù)必須不大于第二個參數(shù)
>>>importrandom
>>>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結束,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.randint來生成一個隨機數(shù)組
importrandom
defrandom_int_list(start,stop,length):
start,stop=(int(start),int(stop))ifstart<=stopelse(int(stop),int(start))
length=int(abs(length))iflengthelse0
random_list=[]
foriinrange(length):
random_list.append(random.randint(start,stop))
returnrandom_list
接下來我們就可以用這個函數(shù)來生成一個隨機的整數(shù)序列了
>>>random_int_list(1,100,10)
[54,13,6,89,87,39,60,2,63,61]
以上內(nèi)容為大家介紹了python培訓之如何用python隨機產(chǎn)生一個一維數(shù)組,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。