Python 内置函数random
random 是 Python 的内置模块,用于生成随机数、随机选择、打乱顺序等常见的随机操作。
函数 | 作用 |
---|---|
random.random() | 生成 0~1 的随机浮点数 |
random.randint(a, b) | 生成 [a, b] 间的随机整数(含两端) |
random.uniform(a, b) | 生成 a~b 的随机浮点数 |
random.choice(seq) | 从序列中随机选择一个元素 |
random.choices(seq, k=3) | 从序列中随机选取 k 个(可重复) |
random.sample(seq, k=3) | 从序列中随机选取 k 个(不重复) |
random.shuffle(seq) | 原地打乱一个列表顺序 |
random.seed(x) | 设置随机种子,使随机结果可复现 |
🧪 示例演示
import randomprint(random.random()) # 0.57412... 随机小数
print(random.randint(1, 10)) # 7 随机整数
print(random.uniform(5, 15)) # 12.32... 随机浮点数colors = ['red', 'green', 'blue']
print(random.choice(colors)) # blue(随机选一个)
print(random.choices(colors, k=2)) # ['green', 'red'](可重复)
print(random.sample(colors, k=2)) # ['red', 'blue'](不重复)nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums) # 可能输出 [3, 1, 5, 2, 4]
想生成一个随机字符串
import random, string
''.join(random.choices(string.ascii_letters + string.digits, k=8))
# 示例:'a3F9xZ1q'
列表推导式
import randoma = 1.0
b = 10.0
n = 5 # 生成 5 个随机浮点数
values = [random.uniform(a, b) for _ in range(n)]
print(values)
📌 补充:使用 numpy.random.uniform(更快、更高效)
import numpy as npa = 1.0
b = 10.0
n = 5values = np.random.uniform(a, b, n)
print(values)