Python——random模块

random 模块

Random variable generators.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>>> random.random()  # 0-1 不包括1 输出一个随机浮点数
0.026446419370216523
>>> random.random()
0.5107952377575242
>>> random.random()
0.8535785412460167

>>> random.randint(1,10) # 取1-10 中的随机一个整数
2
>>> random.randint(1,10) # 取得到10 因为 return self.randrange(a, b+1)
3

>>> random.randrange(1,10)# 取1-10 中的随机一个整数
6 # 但是取不到10
# 原文档
# This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.

>>> random.sample(['1','2','3','4'],2)
['3', '4'] #sample(指定一个范围,随机个数)

>>> l = ['1','2','3','4'] # 打乱原列表的顺序
>>> random.shuffle(l)
>>> l
['4', '2', '1', '3']

>>> random.choice([1,2,3]) # 随机选一个
1
>>> random.choices([1,2,3,4,5,6,7],k = 2) # 随机选择两个
[5, 7]

随机验证码

长度自定义 包括0-9 a-z A-Z


1
2
3
4
5
6
7
8
9
10
11
12
def get_auth_code(length):
res = ""
for i in range(length):
a = random.randint(0,9)
b = chr(random.randint(65,90))
c = chr(random.randint(97,122))
s = random.choice([a,b,c])
res += str(s)
return res

print(get_auth_code(4))
# 5V3l 输出