Python random 模块用来生成随机数、从序列里抽样,以及打乱列表。使用前要 import random。
函数总览
| 函数 | 作用 |
|---|---|
randint | 随机整数(闭区间) |
random | 0~1 浮点数 |
uniform | 区间浮点数 |
choice | 随机选一个 |
sample | 不重复抽样 |
shuffle | 原地打乱 |
seed | 固定随机种子 |
randrange | 区间整数(左闭右开) |
选用要点
- 随机整数:
randint/randrange。 - 随机小数:
random/uniform。 - 从序列选取:
choice/sample。 - 需要结果可复现时,先用
seed固定种子。