常用模块——random模块

random模块——随机数模块

random()

print(random.random())#取随机数范围[0,1)的随机浮点数
#0.11015012425534876

randint()

print(random.randint(1,10))#取限定范围的随机整数,范围[1,10]
#8

randrange()

print(random.randrange(1,10))#取限定范围的随机整数,范围[1,10)
#1

sample()

print(random.sample(['a',1,3,['1','c']],2))#popilation 取值范围,第二参数取值个数,第二参数要小于元素的个数
#[3, ['1', 'c']]

shuffle()

ls = [1,'sd','3','4']
random.shuffle(ls)#随机打乱原来列表的顺序
print(ls)
#['3', 1, 'sd', '4']

choice()

print(random.choice([1,2,3,4]))#从列表中随机取出一个值
#3

choices()

print(random.choices([1,2,3,4,5,6],k=2))#列表中随机取出元素,k=关键字参数指定取值的轮次,每次在限定范围中取一个值,k没有限制
#[5, 3]

应用:随机验证码

#随机验证码
def get_auth_code(length):
    res = ''
    for i in range(length):
        a = random.randint(0,9)
        b = chr(random.randint(65,90))#ascii码中大写数字的编码
        c = chr(random.randint(97,122))#小写字母的编码
        res += str(random.choice([a,b,c]))
    return res

print(get_auth_code(4))
#9f5k
原文地址:https://www.cnblogs.com/msj513/p/9798059.html