【python】【轉】Python產生隨機數的方法

來源:互聯網
上載者:User

標籤:sam   app   偶數   port   隨機   and   .net   ring   form   

 


如果你對在Python產生隨機數與random模組中最常用的幾個函數的關係與不懂之處,下面的文章就是對Python產生隨機數與random模組中最常用的幾個函數的關係,希望你會有所收穫,以下就是這篇文章的介紹。
random.random()用於產生
用於產生一個指定範圍內的隨機符點數,兩個參數其中一個是上限,一個是下限。如果a > b,則產生隨機數
n: a <= n <= b。如果 a <b, 則 b <= n <= a。
print random.uniform(10, 20)
print random.uniform(20, 10)
#----
#18.7356606526
#12.5798298022
random.randint
用於產生一個指定範圍內的整數。其中參數a是下限,參數b是上限,Python產生隨機數
print random.randint(12, 20) #產生的隨機數n: 12 <= n <= 20
print random.randint(20, 20) #結果永遠是20
#print random.randint(20, 10) #該語句是錯誤的。

下限必須小於上限。
random.randrange
從指定範圍內,按指定基數遞增的集合中 ,這篇文章就是對python產生隨機數的應用程式的部分介紹。
隨機整數:
>>> import random
>>> random.randint(0,99)
21
隨機選取0到100間的偶數:
>>> import random
>>> random.randrange(0, 101, 2)
42
隨機浮點數:
>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881
隨機字元:
>>> import random
>>> random.choice(‘abcdefg&#%^*f‘)
‘d‘
多個字元中選取特定數量的字元:
>>> import random
random.sample(‘abcdefghij‘,3)
[‘a‘, ‘d‘, ‘b‘]
多個字元中選取特定數量的字元組成新字串:
>>> import random
>>> import string
>>> string.join(random.sample([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘], 3)).r
eplace(" ","")
‘fih‘
隨機選取字串:
>>> import random
>>> random.choice ( [‘apple‘, ‘pear‘, ‘peach‘, ‘orange‘, ‘lemon‘] )
‘lemon‘
洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]

 

 

來源: http://www.jb51.net/article/45653.htm

【python】【轉】Python產生隨機數的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.