random模块
import random
1.random()方法返回随机浮点数,范围为[0,1)
print(random.random())
结果:0.9538981546464593
2.randint(a,b)方法返回[a,b]之间的一个随机整数
print(random.randint(1,10))
结果:3
3.uniform(a,b)方法返回[a,b]之间的一个随机浮点数
print(random.uniform(1,10))
结果:1.2735791032138195
4.choice(seq)方法,返回从seq序列中的一个随机字符(list、tuple、str)
print(random.choice("tomorrow"))
结果:m
5.randrange(a,b,step)返回 从a到b间隔为2的一个随机整数
print(random.randrange(10,100,2)) 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数
结果:10或者98
random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
6.shuffle(list)方法把序列中的元素打乱,改变原有序列,不生成新数据,应用场景:洗牌
a=[1,3,5,6,7]
random.shuffle([1,3,5,6,7])
print(a)
结果:[5,3,1,6,7]
7.sample(seq,len) 从自定序列中返回指定长度的列表(list、tuple、str),sample不会修改原有序列
list=[1,2,3,4,5,6,7,8,9,10]
slice=random.sample(list,5)#从list中随机获取5个元素,作为一个片断返回
print (slice)
print (list)#原有序列并没有改变。
结果:
[9, 2, 7, 8, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
范例1:生成随机验证码
import random
def generate_verification_code(len=6):
''' 随机生成6位的验证码 '''
# 注意: 这里我们生成的是0-9A-Za-z的列表,当然你也可以指定这个list,这里很灵活
# 比如: code_list = ['P','y','t','h','o','n','T','a','b'] # PythonTab的字母
code_list = []
for i in range(10): # 0-9数字
code_list.append(str(i))
for i in range(65, 91): # 对应从“A”到“Z”的ASCII码
code_list.append(chr(i))
for i in range(97, 123): #对应从“a”到“z”的ASCII码
code_list.append(chr(i))
myslice = random.sample(code_list, len) # 从list中随机获取6个元素,作为一个片断返回
verification_code = ''.join(myslice) # list to string
return verification_code
xxx = generate_verification_code()
print(xxx)
浙公网安备 33010602011771号