python random
时间: 2023-06-21 20:07:27 浏览: 37
`random` 是 Python 内置模块,用于生成随机数或随机序列。可以使用 `import random` 导入该模块。
以下是 `random` 模块常用的函数:
- `randrange()`:生成指定范围内的随机整数。
- `random()`:生成一个介于 0 和 1 之间的随机浮点数。
- `uniform(a, b)`:生成介于 a 和 b 之间的随机浮点数。
- `shuffle(seq)`:将序列 seq 中的元素随机排序。
- `choice(seq)`:从序列 seq 中随机返回一个元素。
- `sample(seq, n)`:从序列 seq 中随机抽取 n 个元素。
示例代码:
```python
import random
# 生成 0 到 9 之间的随机整数
print(random.randrange(10))
# 生成 0 到 1 之间的随机浮点数
print(random.random())
# 生成 -1 到 1 之间的随机浮点数
print(random.uniform(-1, 1))
# 将列表随机排序
lst = [1, 2, 3, 4, 5]
random.shuffle(lst)
print(lst)
# 从列表中随机选择一个元素
lst = ['apple', 'banana', 'orange', 'grape']
print(random.choice(lst))
# 从列表中随机选择两个元素
lst = ['apple', 'banana', 'orange', 'grape']
print(random.sample(lst, 2))
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)