random模块

random模块

  • 定义:随机生成整数 / 小数 / 指定列表值某个元素

【一】随机生成小数

【1】默认区间的小数 区间0-1之间的小数

复制代码
import random
print(random.random())      # 0.5858839340258046

【2】指定区间 给定区间内的小数

复制代码
import random
print(random.uniform(4,8 ))     # 7.467665328012298

【二】随机生成整数

【1】指定区间的整数 给定区间内的整数

复制代码
import random
print(random.randint(1,10))     # 8

【2】随机区间内的奇偶数

复制代码
import random
print(random.randrange(1,20,2))     # 1,3,5
print(random.randrange(1,20,3))     # 2,4,6

【三】随机返回值

【1】返回一个元素

先创建一个可迭代类型

复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choice(num_list))      # 输出abc 或者数字

【2】一次性返回多个元素

(1)以列表的形式返回结果
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list))     # [4]
(2)以指定关键字 k 指定返回列表中的元素个数
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list, k=3))    # ['c', 4, 1]
print(random.choices(num_list, 3))      # 与上面一条命令结果一样,默认值就是k

【四】打乱顺序

random.shuffle()

复制代码
num_list = [i for i in range(1,10)]
print(num_list)             # [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(num_list)    # 打乱顺序
print(num_list)         # [2, 3, 1, 8, 6, 5, 4, 7, 9]
​

【五】随机生成验证码

  • 随机大小写字母 + 随机数字

  • chr(数字) ---> 返回指定ASCII码对应的字符

  • 做一个能生成6位的验证码

复制代码
import random

def v_code(n):
    code=''
    for i in range(n):
        random_int = str(random.randint(0, 9))      # 0~9之间的整数
        random_upper = chr(random.randint(65,90))   # A~Z的大写字母
        random_lower = chr(random.randint(97,122))  # a~z的小写字母
        temp = random.choice([random_int, random_upper, random_lower])
        code += temp
    return code

result = v_code(6)
print(result)
相关推荐
3095566663 分钟前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
AI创界者12 分钟前
Python 进阶实战(七十章):遗留系统重构、渐进式绞杀与技术债治理实战
人工智能·python·aigc
ZhengEnCi1 小时前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
郝学胜-神的一滴2 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
Wellijohn3 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo4 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶4 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')4 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习