random中的主要函數有:
random.random():獲取一個隨機的浮點數,范圍是在0.0~1.0之間
random.uniform():uniform(self, a, b) —— 產生區間內的隨機浮點數
random.randint():randint(self, a, b) —— 生成區間內(包括端點)的整型數據
random.choice():choice(self, seq) —— 隨機取序列的一個元素
random.choices(population,weights=None,*,cum_weights=None,k=1) —— 在原來數據的基礎上隨機選取k次數據,返回一個列表,可以設置權重
random.shuffle():shuffle(self, x, random=None):直接隨機原地打亂數據,返回值是None,因為原值被改變了
random.sample():sample(self, population, k):取原序列中的k個元素
random.randrange(a,b,step):根據一定步長,在區間內隨機取值
random.gauss(self, mu, sigma):生成滿足一定均值mu和標准差sigma的高斯分布浮點數
例子如下:
import random # random.seed(1) a = [1, 2, 'where','天氣','時間','happy new year']
1. random.random()
d = random.random() # 一個隨機的浮點數,范圍是在0.0~1.0之間 print(d)
2. random.uniform()
f = random.uniform(1,3) #產生區間內的隨機浮點數 print(f)
3. random.randint()
e = random.randint(1,7) #生成1-7之間(包括端點)的整型數據 print(e)
4. random.choice()
b = random.choice(a) #隨機取一個元素 print(b)
5. random.choices()
c = random.choices(a, weights=[1,1,1,1,1,1], k=2) #重復在原來的基礎上取k次數據,weights=[1,1,1,1,1,1]表示各個位置的取值概率一致: 1/(1+1+1+1+1+1)=1/6 print(c) c = random.choices(a, weights=[0,0,0,0,0,1], k=2) #為0表示取到該位置的值的概率為0: 0/(0+0+0+0+0+1)=0 print(c) #累計權重cum_weights=[0,1,1,1,1,1],理解的時候最好是轉換一下轉成weights,可以得到:weights=[0,1,0,0,0,0]=[0,1-0,1-1,1-1,1-1,1-1] c = random.choices(a, cum_weights=[0,1,1,1,1,1], k=2) print(c)
6. random.shuffle()
random.shuffle(a) #直接隨機原地打亂數據,返回值是None print(a)
7. random.sample()
# random.sample(population,n) g = random.sample(a,2) #取原序列中的n個元素 print(g)
8. random.randrange()
# random.randrange(a,b,step) j = random.randrange(0,10,2) #步長為2的話,會生成范圍內的隨機偶數 print(j)
9. random.gauss()
h = random.gauss(0,1) # 生成滿足一定均值和標准差的高斯分布浮點數 print(h)
##
參考:
https://www.cnblogs.com/dylancao/p/8202888.html
https://www.sohu.com/a/237831880_697896
https://blog.csdn.net/ckk727/article/details/99548223