
两种写法
random.randrange(stop)
random.randrange(start, stop[, step])# 栗子一
for i in range(5):
print(random.randrange(20))
####
17
4
7
7
4
# 栗子二
for i in range(5):
print(random.randrange(10, 20))
####
13
14
11
17
17
# 栗子三
for i in range(5):
print(random.randrange(10, 20, 2))
####
12
12
14
14
10a <= N <= brandrange(a, b+1)random.randint(a, b)for i in range(5):
print(random.randint(0,20))
####
19
20
11
6
3a、b 都可以取得到哦
返回 [0.0, 1.0) 范围内的下一个随机浮点数
random.random()# 栗子一
for i in range(5):
print(random.random())
####
0.9829492243165335
0.43473506430105724
0.5198709187243076
0.6437884305820736
0.7216771961168909
# 栗子二
for i in range(5):
print(math.ceil(random.random() * 1000))
####
772
352
321
62
127a <= b 时,a <= N <= bb < a 时, b <= N <= arandom.uniform(a, b)# 栗子一
for i in range(5):
print(random.uniform(1, 10))
####
2.6200262089754593
9.220506911469235
3.0206896704014783
9.670905330339174
1.170694187192196
# 栗子二
for i in range(5):
print(random.uniform(8, 2))
####
2.696842757954265
6.058794935110275
7.567631220015144
2.2057698202258074
4.454083664106361random.choice(seq)# 数字数组
print(random.choice([1, 2, 3, 4, 5]))
# 字母数组
print(random.choice(["a", "b", "c"]))
# 字母元组
print(random.choice(("a", "b", "c")))
# 字符串
print(random.choice("abcdef"))
# string 模块返回的大小写字母字符串
print(random.choice(string.ascii_letters))
# string 模块返回的数字字符串
print(random.choice(string.digits))
# string 模块返回的数字字符串+大小写字母字符串
print(random.choice(string.digits + string.ascii_uppercase))
####
5
c
c
e
l
2
Frandom.choices(population, weights=None, *, cum_weights=None, k=1) 看的迷迷糊糊啥意思。。?来看栗子。。
a = [1,2,3,4,5]
print(random.choices(a,k=5))
# 结果
[5, 5, 3, 1, 5]可以重复取元素
a = [1, 2, 3, 4, 5]
print(random.choices(a, weights=[0, 0, 1, 0, 0], k=5))
# 结果
[3,3,3,3,3]a = [1, 2, 3, 4, 5]
print(random.choices(a, weights=[0, 2, 1, 0, 0], k=5))
# 结果
[2, 2, 2, 2, 3]2 的权重更大,所以取到它的概率更高
a = [1, 2, 3, 4, 5]
print(random.choices(a, cum_weights=[1, 1, 1, 1, 1], k=5))
print(random.choices(a, cum_weights=[1, 4, 4, 4, 4], k=5))
print(random.choices(a, cum_weights=[1, 2, 3, 4, 5], k=5))
# 结果
[1, 1, 1, 1, 1]
[2, 2, 1, 2, 1]
[5, 5, 1, 4, 2]是不是看不懂?我也看不懂,但其实就是普通权重相加而已
random.shuffle(x[, random])# 数字数组
a = [1, 2, 3, 4, 5]
random.shuffle(a)
print(a)
# 字母数组
b = ["a", "b", "c"]
random.shuffle(b)
print(b)
####
[3, 5, 2, 4, 1]
['a', 'c', 'b']random.sample(population, k)全都是 k=3
# 数字数组
print(random.sample([1, 2, 3, 4, 5], 3))
# 字母数组
print(random.sample(["a", "b", "c"], 3))
# 字母元组
print(random.sample(("a", "b", "c"), 3))
# 字符串
print(random.sample("abcdef", 3))
# string 模块返回的大小写字母字符串
print(random.sample(string.ascii_letters, 3))
# string 模块返回的数字字符串
print(random.sample(string.digits, 3))
# string 模块返回的数字字符串+大小写字母字符串
print(random.sample(string.digits + string.ascii_uppercase, 3))
####
[2, 1, 3]
['b', 'c', 'a']
['a', 'b', 'c']
['a', 'f', 'b']
['M', 'w', 'W']
['7', '1', '5']
['R', '8', 'O']