Python隨機(jī)數(shù)用法實例詳解【基于random模塊】
本文實例講述了Python隨機(jī)數(shù)用法。分享給大家供大家參考,具體如下:
1. random.seed(int)
給隨機(jī)數(shù)對象一個種子值,用于產(chǎn)生隨機(jī)序列。
對于同一個種子值的輸入,之后產(chǎn)生的隨機(jī)數(shù)序列也一樣。
通常是把時間秒數(shù)等變化值作為種子值,達(dá)到每次運(yùn)行產(chǎn)生的隨機(jī)系列都不一樣
seed() 省略參數(shù),意味著使用當(dāng)前系統(tǒng)時間生成隨機(jī)數(shù)
random.seed(10) print random.random() #0.57140259469 random.seed(10) print random.random() #0.57140259469 同一個種子值,產(chǎn)生的隨機(jī)數(shù)相同 print random.random() #0.428889054675 random.seed() #省略參數(shù),意味著取當(dāng)前系統(tǒng)時間 print random.random() random.seed() print random.random()
2. random.randint(a,b)
返回指定范圍的一個隨機(jī)整數(shù),包含上下限
print random.randint(1,10)
3. random.uniform(u,sigma)
隨機(jī)正態(tài)浮點(diǎn)數(shù)
print random.uniform(1,5)
4. random.randrange(start,stop,step)
按步長隨機(jī)在上下限范圍內(nèi)取一個隨機(jī)數(shù)
print random.randrange(20,100,5)
5. random.random()
隨機(jī)浮點(diǎn)數(shù)
print random.random()
6. 隨機(jī)選擇字符
隨機(jī)的選取n個字符
print random.sample('abcdefghijk',3)
隨機(jī)的選取一個字符
print random.choice('abcde./;[fgja13ds2d')
隨機(jī)選取幾個字符,再拼接成新的字符串
print string.join(random.sample('abcdefhjk',4)).replace(" ","")
7.random.shuffle
對list列表隨機(jī)打亂順序,也就是洗牌
shuffle只作用于list,對Str會報錯比如‘a(chǎn)bcdfed',而['1','2','3','5','6','7']可以
item=[1,2,3,4,5,6,7] print item random.shuffle(item) print item item2=['1','2','3','5','6','7'] print item2 random.shuffle(item2) print item2
PS:這里再為大家提供兩款相關(guān)在線工具供大家參考使用:
在線隨機(jī)數(shù)字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高強(qiáng)度密碼生成器:
http://tools.jb51.net/password/CreateStrongPassword
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
pytorch教程之Tensor的值及操作使用學(xué)習(xí)
這篇文章主要為大家介紹了pytorch教程中關(guān)于Tensor的操作使用,有需要的朋友可以借鑒參考下,希望可以有所幫助,祝大家升職加薪,共同進(jìn)步2021-09-09python實現(xiàn)簡單聊天應(yīng)用 python群聊和點(diǎn)對點(diǎn)均實現(xiàn)
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)簡單聊天應(yīng)用,python群聊和點(diǎn)對點(diǎn)均實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09tensorflow使用神經(jīng)網(wǎng)絡(luò)實現(xiàn)mnist分類
這篇文章主要為大家詳細(xì)介紹了tensorflow使用神經(jīng)網(wǎng)絡(luò)實現(xiàn)mnist分類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09