新聞中心

在安康等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè) 網(wǎng)站設(shè)計(jì)制作定制網(wǎng)站制作,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),全網(wǎng)整合營銷推廣,外貿(mào)網(wǎng)站建設(shè),安康網(wǎng)站建設(shè)費(fèi)用合理。
一、最直接的方式:用numpy.random模塊來生成隨機(jī)數(shù)組
1、np.random.rand 用于生成[0.0, 1.0)之間的隨機(jī)浮點(diǎn)數(shù), 當(dāng)沒有參數(shù)時(shí),返回一個(gè)隨機(jī)浮點(diǎn)數(shù),當(dāng)有一個(gè)參數(shù)時(shí),返回該參數(shù)長度大小的一維隨機(jī)浮點(diǎn)數(shù)數(shù)組,參數(shù)建議是整數(shù)型,因?yàn)槲磥戆姹镜膎umpy可能不支持非整形參數(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ù)返回一個(gè)樣本,具有標(biāo)準(zhǔn)正態(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]) 返回隨機(jī)的整數(shù),位于半開區(qū)間 [low, high)。
>>> np.random.randint(10,size=10) array([4, 1, 4, 3, 8, 2, 8, 5, 8, 9])
相關(guān)推薦:《python入門教程》
4、random_integers(low[, high, size]) 返回隨機(jī)的整數(shù),位于閉區(qū)間 [low, high]。
>>> np.random.random_integers(5) 2
5、 np.random.shuffle(x) 類似洗牌,打亂順序;np.random.permutation(x)返回一個(gè)隨機(jī)排列
>>> 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) -> 返回一個(gè)位于[low,hight]之間的整數(shù)
該函數(shù)接受兩個(gè)參數(shù),這兩個(gè)參數(shù)必須是整數(shù)(或者小數(shù)位是0的浮點(diǎn)數(shù)),并且第一個(gè)參數(shù)必須不大于第二個(gè)參數(shù)
>>> import random >>> random.randint(1,10) 6 >>> random.randint(1.0, 10.0) 1
2、random.random() -> 不接受參數(shù),返回一個(gè)[0.0, 1.0)之間的浮點(diǎn)數(shù)
>>> random.random() 0.5885821552646049
3、random.uniform(val1, val2) -> 接受兩個(gè)數(shù)字參數(shù),返回兩個(gè)數(shù)字區(qū)間的一個(gè)浮點(diǎn)數(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為步長的列表中的隨機(jī)整數(shù),同樣,三個(gè)參數(shù)均為整數(shù)(或者小數(shù)位為0),若start大于stop時(shí) ,setp必須為負(fù)數(shù).step不能是0.
>>> random.randrange(1, 100, 2) #返回[1,100]之間的奇數(shù) 19 >>> random.ranrange(100, 1, -2) #返回[100,1]之間的偶數(shù) 2
5、生成隨機(jī)數(shù)組
使用random.randint方法構(gòu)造一個(gè)列表即可:
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
分享標(biāo)題:創(chuàng)新互聯(lián)Python教程:pythonlist怎樣生成隨機(jī)數(shù)
URL標(biāo)題:http://m.fisionsoft.com.cn/article/cccceip.html


咨詢
建站咨詢
