Python隨機數用法執行個體詳解【基於random模組】,pythonrandom

來源:互聯網
上載者:User

Python隨機數用法執行個體詳解【基於random模組】,pythonrandom

本文執行個體講述了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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.