Python的随即模块random

发布时间 2023-12-07 22:49:12作者: JessicaJJmm

1、随机小数

import random
# 大于0且小于1之间的小数
res = random.random()
print(res) # 0.6102580330717722
 
#大于10小于88的小数
res1 = random.uniform(10,88)
print(res1)  # 75.87387536787733

 

2、随机整数

# 大于等于1且小于等于5之间的整数
res = random.randint(1,10) 
print(res)
 
# 大于等于1且小于10之间的奇数
res1 = random.randrange(1,10,2)
print(res1)

 

3、随机选择一个返回

从可迭代对象中返回元素,可以指定返回几个,以列表形式输出

res = random.choice([1, '23', [4, 5]])
# print(res)
 
random.sample(population, k)
# population:表示要从中选择的序列,可以是列表、元组、集合或其他可迭代对象。
# k:表示要选择的元素数量,必须是一个非负整数,并且不大于 population 的长度
res1 = random.sample([1,'23',[4,5],'name'],3)
print(res1)

 

4、打乱列表顺序

item=[1,3,5,7,9]
random.shuffle(item) # 打乱次序
print(item) # [9, 5, 7, 1, 3]

 

5、随机验证码

import random
 
def v_code():
    code = ''
    for i in range(7):
        num = random.randint(0, 9)  # 随机返回整数
        alf = chr(random.randint(65, 122))  # 随机返回65到90之间的整数,对应编码表a到z的
        add = random.choice([num, alf])
        code = "".join([code, str(add)])
 
    return code
# print(ord('a'))  # 97
# print(ord('z'))  # 122
# print(ord('A'))  # 65
# print(ord('Z'))  # 90
print(v_code())