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")!
相关推荐
花酒锄作田5 小时前
[python]argparse 包在聊天机器人中的应用
python
一尘之中7 小时前
从C语言底层设计到系统架构评估:软件架构知识体系全景
学习·系统架构·ai写作
NiceCloud喜云7 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
AI玫瑰助手8 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
weixin_468466858 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
油炸自行车8 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋8 小时前
C++14特性
开发语言·c++·c++14特性
小糖学代码8 小时前
LLM系列:环境搭建:5.Python-dotenv 环境变量管理
人工智能·python·深度学习·神经网络
星夜夏空999 小时前
FreeRTOS学习(4)——内存映射
数据库·学习·mongodb
智慧物业老杨9 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python