一 前言
本篇主講內容爲python基礎模塊random庫的基本使用,讀者熟悉基本用法即可,需要特殊要求查詢官方文檔即可
知識追尋者(Inheriting the spirit of open source, Spreading technology knowledge;)
二 random模塊
random 模塊即提供多種樣式的隨機數;
2.1 random 函數
random() 產生 [0,1) 的浮點數
import random
# 0.23995213660548942
print(random.random())
2.2 randint函數
randint(a,b) 產生 [a,b] 範圍內的整數
import random
# 840
print(random.randint(100, 999))
2.3 randrange函數
randrange(start, stop, step) 如下示例,步長爲2 ,產生[0,11]之間任意一個偶數;
import random
# 2
print(random.randrange(0, 11, 2))
2.4 uniform函數
uniform(start, stop);產生 [5,10] 之間任意一個浮點數;
import random
# 5.836304369503202
print(random.uniform(5, 10))
2.5 sample函數
sample(sequence, k); 從序列中隨意抽取 k 個字符組成列表;
import random
# ['z', 'x']
print(random.sample('zszxz', 2))
2.6 choice函數
choice(sequence) ; 從 序列中隨意抽取一個字符;
import random
alpha = ['a', 'b', 'c', 'd', 'e']
# b
print(random.choice(alpha))
2.7shuffle函數
shuffle(x,random); 將有序列表進行隨機排序
import random
random.shuffle(alpha)
# ['e', 'a', 'b', 'd', 'c']
print(alpha)
三 官方文檔
https://docs.python.org/zh-cn/3.8/library/random.html