random
模块实用教程random
模块是 Python 标准库中用于生成伪随机数的模块,它提供了多种随机数生成和随机操作功能。虽然 NumPy 的随机模块功能更强大,但在不需要复杂数值计算或不想引入外部依赖时,内置的 random
模块仍然是一个非常方便的选择。
random
模块提供了以下主要功能:
import random
# 生成 [0.0, 1.0) 之间的随机浮点数
print(random.random()) # 例如 0.5488135039273248
# 生成 [a, b] 之间的随机浮点数
print(random.uniform(1.5, 3.5)) # 例如 2.7830182145213975
# 生成 [a, b] 之间的随机整数
print(random.randint(1, 10)) # 例如 7
# 从序列中随机选择一个元素
print(random.choice(['apple', 'banana', 'orange'])) # 例如 'banana'
# 从序列中随机选择多个不重复元素
print(random.sample(range(100), 5)) # 例如 [82, 16, 4, 21, 89]
伪随机数生成器可以通过设置种子来重现随机序列:
random.seed(42) # 设置随机种子
print(random.random()) # 总是 0.6394267984578837
print(random.random()) # 总是 0.025010755222666936
random.seed(42) # 重置相同的种子
print(random.random()) # 再次得到 0.6394267984578837
random
模块支持多种概率分布的随机数生成。
# [a, b) 之间的均匀分布浮点数
print(random.uniform(2.5, 5.5))
# 正态分布,参数为 mu(均值) 和 sigma(标准差)
print(random.gauss(0, 1)) # 标准正态分布
# 另一种正态分布函数
print(random.normalvariate(0, 1))
# 指数分布,参数 lambda(速率参数)
print(random.expovariate(1.5))
# 三角分布
print(random.triangular(low=1.0, high=5.0, mode=3.0))
# 对数正态分布
print(random.lognormvariate(mu=0.0, sigma=1.0))
# 冯·米塞斯分布(圆形正态分布)
print(random.vonmisesvariate(mu=0.0, kappa=1.0))
# 伽马分布
print(random.gammavariate(alpha=2.0, beta=1.0))
# 帕累托分布
print(random.paretovariate(alpha=1.0))
# 韦伯分布
print(random.weibullvariate(alpha=1.0, beta=1.0))
items = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(items) # 原地打乱
print(items) # 例如 [3, 1, 7, 2, 5, 6, 4]
# 根据权重随机选择
population = ['red', 'green', 'blue']
weights = [0.6, 0.3, 0.1]
print(random.choices(population, weights, k=5))
# 例如 ['red', 'red', 'green', 'red', 'red']
# 累积权重版本
cum_weights = [0.6, 0.9, 1.0]
print(random.choices(population, cum_weights=cum_weights, k=5))
# 生成指定长度的随机字节串
print(random.randbytes(4)) # 例如 b'\x9d\x9f\x7f\xef'
# 以给定概率返回True
print(random.random() < 0.7) # 70%概率为True
# 更简洁的写法
print(random.choices([True, False], weights=[0.7, 0.3])[0])
import random
import string
def generate_captcha(length=6):
# 混合字母和数字
chars = string.ascii_letters + string.digits
# 排除容易混淆的字符
confusing = {'0', 'O', 'o', '1', 'I', 'l'}
chars = [c for c in chars if c not in confusing]
return ''.join(random.choices(chars, k=length))
print(generate_captcha(8)) # 例如 'X3hK9pY2'
import random
import string
def generate_password(length=12):
# 确保包含各类字符
lower = random.choice(string.ascii_lowercase)
upper = random.choice(string.ascii_uppercase)
digit = random.choice(string.digits)
punct = random.choice(string.punctuation)
# 剩余字符
remaining = length - 4
chars = string.ascii_letters + string.digits + string.punctuation
others = random.choices(chars, k=remaining)
# 组合并打乱
password = list(lower + upper + digit + punct + ''.join(others))
random.shuffle(password)
return ''.join(password)
print(generate_password()) # 例如 'sD7@kL9#qP2!'
import random
def estimate_pi(n=1000000):
inside = 0
for _ in range(n):
x, y = random.random(), random.random()
if x**2 + y**2 <= 1:
inside += 1
return 4 * inside / n
print(estimate_pi()) # 例如 3.141592
# 低效方式
numbers = []
for _ in range(10000):
numbers.append(random.random())
# 高效方式 - 使用列表推导式仍然比循环快
numbers = [random.random() for _ in range(10000)]
# 对于大量随机数,考虑使用NumPy
# import numpy as np
# numbers = np.random.random(10000)
# 不推荐 - 频繁设置种子会破坏随机性
for i in range(10):
random.seed(42)
print(random.random())
# 推荐 - 只设置一次种子
random.seed(42)
for i in range(10):
print(random.random())
random
模块生成的是伪随机数,不适合安全或加密用途:
# 不适用于安全场景
import random
print(''.join(random.choices('0123456789', k=6))) # 可预测
# 安全场景应使用secrets模块
import secrets
print(''.join(secrets.choice('0123456789') for _ in range(6))) # 安全随机
特性 | Python random |
NumPy random |
---|---|---|
基本随机数 | 支持 | 支持 |
多种概率分布 | 有限支持 | 更全面支持 |
向量化操作 | 不支持 | 支持 |
性能 | 一般 | 更高 |
依赖 | 内置模块 | 需要安装NumPy |
随机种子管理 | 简单 | 更复杂 |
Python 内置的 random
模块虽然功能上不如 NumPy 的随机模块强大,但在许多场景下仍然非常有用:
记住:
random
模块完全够用secrets
模块通过合理使用 random
模块,可以在不增加项目复杂度的前提下,实现大多数常见的随机功能需求。