python 标准库random生成随机数


当前版本:

  • Python 3.8.4

文章目录如下

[1. random的特点](#1. random的特点)

[2. random的用法](#2. random的用法)

[2.1. 随机整数](#2.1. 随机整数)

[2.2. 随机小数](#2.2. 随机小数)

[2.3. 随机元素](#2.3. 随机元素)

[2.4. 随机字符串](#2.4. 随机字符串)


1. random的特点

random 提供了生成伪随机数的功能,可以用于各种随机相关的操作,如生成随机数、洗牌、选择随机元素等。常用的内置方法如下:

【随机整数】

python 复制代码
import random
random.randint(x, y)   # x~y之间的随机整数
random.randrange(start, stop[, step])  # 指定范围内的随机整数,可指定起始值、终止值和步长。

【随机浮点数】

python 复制代码
import random
random.random()        # 0~1随机浮点数
random.uniform(x, y)   # x~y之间的随机浮点数

【随机元素】

python 复制代码
import random
random.choice(seq)    # 序列中随机选择一个元素
random.shuffle(seq)   # 随机打乱序列中的元素的顺序

2. random的用法

2.1. 随机整数

随机整数一般通过 randint 或 randrange 来获取,它们的范围由平台位数决定:

python 复制代码
32位范围:(-2^31) ~ (2^31 - 1)  # -2147483648 ~ 2147483647

64位范围:(-2^63) ~ (2^63 - 1)  # -9223372036854775808 ~ 9223372036854775807

常用的 randint 语法:

python 复制代码
random.randint(开始大小, 结束大小)

比如指定获取 0~1

python 复制代码
random.randint(0, 1)

生成6位随机数

python 复制代码
random.randint(100000, 999999)

在一些特定的场合需要指定步长可以利用randrange来获取

python 复制代码
random.randrange(开始大小,结束大小,步长)

比如取1~100的随机奇数

python 复制代码
random.randrange(1,100,2)

取1~100随机偶数

python 复制代码
random.randrange(0,100,2)

2.2. 随机小数

  • 随机小数可以通过 random 或 uniform 获取

【案例一】生成0~1的随机小数 random

python 复制代码
random.random()    # 不接受参数

也支持运算(生成1~100的小数)

【案例二】按范围生成随机小数 uniform

python 复制代码
random.uniform(1, 10)    # 指定开始值和结束值

【案例三】指定小数位为2 round

python 复制代码
round(random.uniform(1, 10), 2)

2.3. 随机元素

【案例一】通过 choice 来获取一个随机元素

python 复制代码
L = [ "AAA", "BBB", 200, "CCC" ]
random.choice(L)    # 传入一个序列

【案例二】通过 shuffle 将序列的元素顺序打乱

python 复制代码
L = [ "AAA", "BBB", 200, "CCC" ]
random.shuffle(L)    # 传入一个序列

【案例三】通过 sample 随机获取n个元素

python 复制代码
L = [1, 2, 3, 4, 5]
random.sample(L, 3)

2.4. 随机字符串

choices 方法可以通过自定义的字符来生成一个列表,语法如下:

python 复制代码
random.choices('自定义字符', k=长度)

例如

python 复制代码
random.choices('abcdef', k=3)
  • 随机从 'abcdef' 中选取3个字符组成一个列表

生成字符串的话需要借助 join 函数

python 复制代码
''.join(random.choices('abcdef', k=3))

如果希望内容丰富一点,那就自定义多一些字符

python 复制代码
random_string = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=6))
相关推荐
数据智能老司机几秒前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 分钟前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 分钟前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i11 分钟前
drf初步梳理
python·django
每日AI新事件11 分钟前
python的异步函数
python
这里有鱼汤1 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook10 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室11 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三12 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271116 小时前
Python之语言特点
python