Python的random随机模块相关学习记录

random是有关随机功能的一个内置模块

bash 复制代码
import random

# 获取0-1之间的随机小数
print(random.random())  # 0.6224750165089413
# 获取0-1之间的随机小数


# a-----b之间的随机小数
a = 0
b = 10
print(random.uniform(a, b))  # 1.25491670861257

# 两边的值都包含在内,获取两个值包括两个值之间的任意整数
print(random.randint(1, 100))  # 85   1    100

# 两个值之间的任意整数(顾头不顾尾)
print(random.randrange(1, 100))  # 1   99

# 序列中选一个
print(random.choice([1, 2, 3, 4, 5, 6]))  # 2


# 可变容器中的元素打乱顺序(必须是可变类型)
li = [1, 2, 3, 4, 5, 6]
random.shuffle(li)
print(li)    # [4, 5, 2, 6, 3, 1]

# chr将某个unicode编码值转化成他所代表的字符
print(chr(97))     # a

# ord将某个字符转化成他对应的unicode编码值
print(ord("a"))     # 97


# 生成一个16位的随机密码包含  数字,大小写字母 符号
def create_random_password(str_count):
    password = ''
    char_list = [[97, 122], [65, 90], [48, 57], [33, 47]]
    for i in range(str_count):
        ret = random.choice(char_list)
        password += chr(random.randint(ret[0], ret[1]))
    return password


print(create_random_password(16))    #  WJo6%#&Wr'#.4")!
相关推荐
花酒锄作田8 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪12 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽12 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战13 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋18 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama