模块之random模块详解

random模块的使用

random是Python内置模块, 想要使用该模块, 第一步需要进行导入, 下面介绍几种random常用的函数

import random

print(random.random())  # 大于0且小于1之间的小数

print(random.randint(1, 3)) # [1, 3]  大于等于1且小于等于3之间的整数

print(random.randrange(1, 3))  # [1, 3)  大于等于1且小于3之间的整数

print(random.choice([1, 'a', [4, 5]]))  # 1或a或[4, 5]

print(random.sample([1, 'a', 'b', 'c', 'd'], 2))  # 列表元素任意2个组合

print(random.uniform(1, 3))  # 大于1小于3的小数

item = [1, 3, 5, 7, 9]

random.shuffle(item)  # 打乱item的顺序, 相当于"洗牌"
print(item)

random模块的应用

对于生成随机验证码, 可以使用random模块进行处理, 具体示例代码如下:

import random


def make_code(size=4):
    res = ''
    for i in range(size):
        s1 = chr(random.randint(65, 90))
        s2 = str(random.randint(0, 9))
        res += random.choice([s1, s2])

    return res


print(make_code(4))
原文地址:https://www.cnblogs.com/featherwit/p/13273594.html