本文實例講述了Python隨機數用法。分享給大家供大家參考,具體如下:
1. random.seed(int)
給隨機數對象一個種子值,用于產生隨機序列。
對于同一個種子值的輸入,之后產生的隨機數序列也一樣。
通常是把時間秒數等變化值作為種子值,達到每次運行產生的隨機系列都不一樣
seed() 省略參數,意味著使用當前系統時間生成隨機數
random.seed(10)print random.random() #0.57140259469random.seed(10)print random.random() #0.57140259469 同一個種子值,產生的隨機數相同print random.random() #0.428889054675random.seed() #省略參數,意味著取當前系統時間print random.random()random.seed()print random.random()
2. random.randint(a,b)
返回指定范圍的一個隨機整數,包含上下限
print random.randint(1,10)
3. random.uniform(u,sigma)
隨機正態浮點數
print random.uniform(1,5)
4. random.randrange(start,stop,step)
按步長隨機在上下限范圍內取一個隨機數
print random.randrange(20,100,5)
5. random.random()
隨機浮點數
print random.random()
6. 隨機選擇字符
隨機的選取n個字符
print random.sample('abcdefghijk',3)隨機的選取一個字符
print random.choice('abcde./;[fgja13ds2d')隨機選取幾個字符,再拼接成新的字符串
print string.join(random.sample('abcdefhjk',4)).replace(" ","")7.random.shuffle
對list列表隨機打亂順序,也就是洗牌
shuffle只作用于list,對Str會報錯比如‘abcdfed',而['1','2','3','5','6','7']可以
item=[1,2,3,4,5,6,7]print itemrandom.shuffle(item)print itemitem2=['1','2','3','5','6','7']print item2random.shuffle(item2)print item2
PS:這里再為大家提供兩款相關在線工具供大家參考使用:
在線隨機數字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高強度密碼生成器:
http://tools.jb51.net/password/CreateStrongPassword
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答