如何使用Python中的random模块生成随机数

在Python中,random模块提供了多种用于生成随机数的函数。以下是一些基本示例:

  1. 生成随机整数

使用random.randint(a, b)函数生成一个介于ab之间的随机整数(包括ab)。

复制代码

python复制代码

|---|---------------------------------------------------------|
| | import random |
| | |
| | random_int = random.randint(1, 10) # 生成一个1到10之间的随机整数 |
| | print(random_int) |

使用random.randrange(a, b)函数也可以生成一个介于ab之间的随机整数,但b是不包括在内的。random.randrange(a, b, step)还可以指定步长。

复制代码

python复制代码

|---|----------------------------------------------------------------|
| | random_int = random.randrange(1, 10) # 生成一个1到9之间的随机整数 |
| | print(random_int) |
| | |
| | random_int_step = random.randrange(0, 10, 2) # 生成一个0到8之间的偶数 |
| | print(random_int_step) |

  1. 生成随机浮点数

使用random.random()函数生成一个介于0.0和1.0之间的随机浮点数。

复制代码

python复制代码

|---|---------------------------------------------------------|
| | random_float = random.random() # 生成一个0.0到1.0之间的随机浮点数 |
| | print(random_float) |

使用random.uniform(a, b)函数生成一个介于ab之间的随机浮点数。

复制代码

python复制代码

|---|--------------------------------------------------------------------|
| | random_float = random.uniform(1.0, 10.0) # 生成一个1.0到10.0之间的随机浮点数 |
| | print(random_float) |

  1. 从列表中随机选择元素

使用random.choice(seq)函数从非空序列(如列表、元组或字符串)中随机选择一个元素。

复制代码

python复制代码

|---|----------------------------------------------------------|
| | my_list = [1, 2, 3, 4, 5] |
| | random_choice = random.choice(my_list) # 从列表中随机选择一个元素 |
| | print(random_choice) |

使用random.shuffle(x)函数可以将列表x中的元素随机排序。注意,这个函数会直接修改列表x,而不返回新的列表。

复制代码

python复制代码

|---|------------------------------------------|
| | my_list = [1, 2, 3, 4, 5] |
| | random.shuffle(my_list) # 将列表中的元素随机排序 |
| | print(my_list) |

  1. 生成随机样本

使用random.sample(population, k)函数从非空序列population中随机选择k个不重复的元素。

复制代码

python复制代码

|---|-----------------------------------------------------------------|
| | my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| | random_sample = random.sample(my_list, 3) # 从列表中随机选择3个不重复的元素 |
| | print(random_sample) |

这些只是random模块中提供的一些基本功能。根据你的具体需求,你还可以探索该模块中的其他函数和功能。

相关推荐
曲幽8 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805113 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon14 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly14 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程14 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python