python學習筆記10--random模塊

random模塊是python中的僞隨機數生成模塊,可以通過import random獲取,學習幾個常見的函數:

1. random():隨機生成一個floating point數,範圍在[0.0, 1.0)區間內;

2. uniform(a,b):當a<=b時,隨機生成一個範圍在[a,b]內的floating point數;當a>b時,隨機生成一個範圍在[b,a]內的floating point 數;公式是 a + (b-a)*random();

3. randint(a,b):隨機生成一個整數,範圍在[a,b]區間內;

4. randrang(a,b[,step]):隨機生成一個整數,範圍在[a,b)內,且步長爲step;

5. sample(population,k):population是一個序列或列表,從population中隨機選擇k個值作爲新的列表返回,不改變population的值;

6. choice(sequence):從一個非空序列或列表中,隨機選擇一個值返回,如果序列爲空,返回IndexError。

簡單的例子:

import random
print (random.random())           # 0.620600769037324
print (random.uniform(2,8))       # 4.758365602120907
print (random.randint(1,10))      # 5
print (random.randrange(1,10))    # 9
print (random.choice("abc"))      # b
print (random.choice([1,2,3]))    # 1
print (random.sample([1,2,3,4],2))# [4, 3]
print (random.sample(range(1000),10)) # [799, 307, 887, 667, 862, 909, 362, 375, 198, 906]
print (random.sample("abcdefg",7))    # ['c', 'e', 'g', 'b', 'f', 'd', 'a']


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章