当前版本:
- 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))
