import random
一、实值分布
1.
random.random()
功能:返回 [0.0, 1.0) 范围内的下一个随机浮点数。
random.random()
0.7171059617072177
2.
random.uniform(a,b)
返回一个随机浮点数 N ,当 a <= b 时 a <= N <= b ,当 b < a 时 b <= N <= a 。
等式 a + (b-a) * random() 中的浮点舍入,决定了终点 b 是否会包含在该范围内。
random.uniform(10,100)
96.66020869227908
3.
random.randint(a,b)
功能:返回随机整数 N 满足 a <= N <= b。相当于 randrange(a, b+1)
注意:返回值区间为[a,b]
random.randint(10,11)
11
4.
random.randrange(a,b)
功能:返回一个整数N,并且a <= N<= b-1,区间:[a,b)
random.randrange(1,3) # 等价于random.choice(range(1,3))
1
2
二、随机抽样
1.
random.sample(population, k, *, counts=None)
功能: 用于无重复随机抽样
参数:
- population:总体
- k:抽样个数
- counts:指定总体中元素的重复次数(重点理解)
s = 'abcdefghijklmn'
random.sample(s,5)
['j', 'b', 'f', 'l', 'n']
# 指定总体中元素的重复次数
ss = ["red", "green", "yellow"]
random.sample(ss,7,counts=[1,3,5]) # 等价于random.sample(['red', 'green', 'green', 'green','yellow', 'yellow','yellow','yellow','yellow'])
['yellow', 'yellow', 'green', 'green', 'yellow', 'green', 'red']
# 如果想要将原序列打乱并返回一个新的打乱的序列,可使用
sss = "abcde"
random.sample(sss,k=len(sss))
['d', 'c', 'e', 'b', 'a']
2.
random.shuffle(x)
功能:打乱原序列,注意该函数直接操作的原序列,没有返回值
s1 = [1,2,3,4,5]
random.shuffle(s1)
s1
[4, 2, 1, 3, 5]
3.
random.choice(seq)
功能:从非空序列 seq 返回一个随机元素
s2 = "abcdef"
random.choice(s2)
'c'
4.
random.choices(population, weights=None, *, cum_weights=None, k=1)
功能:有放回的抽样
参数:
- population:总体
- weights:相对权重值
- cum_weights: 累计权重值
- k:抽样个数
s3 = "12345"
random.choices(s3,weights=[10,30,50,80,100],k=1)
['5']
# 相对权重weights
res = random.choices(s3,weights=[1,3,5,10,20],k=10000)
[res.count(i) for i in s3]
[244, 765, 1245, 2522, 5224]
# 累计权重cum_weights
res = random.choices(s3,cum_weights=[1,4,5,10,20],k=10000)
[res.count(i) for i in s3] # [368, 1192, 1850, 2949, 3641]
[500, 1515, 522, 2497, 4966]