avatar

RWO.cc

读一次写一次

  • 首页
  • 搭建手册
  • 笔记
  • 短视频
  • 关于
  • 🌈200粉丝🌈
Home Python 中的 random 模块的常用方法
文章

Python 中的 random 模块的常用方法

Posted 2024-10-14 Updated 2024-10- 13
By RWO.
11~14 min read

random 模块提供了生成随机数、实现随机乱序和随机抽样的方法。以下是一些常用的方法及其示例,包括加上权重、不允许重复以及使用累加权重的情形:

生成随机数

生成一个 [0.0, 1.0) 之间的随机浮点数

import random
print(random.random())

生成指定范围内的随机整数

import random
print(random.randint(1, 10))  # 生成1到10之间的随机整数

生成指定范围内的随机浮点数

import random
print(random.uniform(1.0, 10.0))  # 生成1.0到10.0之间的随机浮点数

实现随机乱序

将列表中的元素打乱顺序

import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

随机抽样

从列表中随机抽取指定数量的元素

import random
my_list = [1, 2, 3, 4, 5]
sample = random.sample(my_list, 2)  # 从 my_list 中随机抽取 2 个元素
print(sample)

从列表中随机选择一个元素

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

从列表中随机选择多个元素(允许重复)

import random
my_list = [1, 2, 3, 4, 5]
choices = random.choices(my_list, k=3)  # 从 my_list 中随机选择 3 个元素(允许重复)
print(choices)

从列表中随机选择多个元素(不允许重复)

import random
my_list = [1, 2, 3, 4, 5]
choices = random.sample(my_list, 3)  # 从 my_list 中随机选择 3 个元素(不允许重复)
print(choices)

加上权重的随机抽样

从列表中随机选择一个元素,带权重

import random
my_list = [1, 2, 3, 4, 5]
weights = [10, 1, 1, 1, 1]  # 第一个元素的权重较大
choice = random.choices(my_list, weights=weights, k=1)
print(choice)

从列表中随机选择多个元素,带权重(允许重复)

import random
my_list = [1, 2, 3, 4, 5]
weights = [10, 1, 1, 1, 1]  # 第一个元素的权重较大
choices = random.choices(my_list, weights=weights, k=3)
print(choices)

从列表中随机选择多个元素,带权重(不允许重复)

由于 random.sample 不支持权重参数,我们可以通过自定义函数来实现:

import random

def weighted_sample(population, weights, k):
    assert len(population) == len(weights)
    choices = set()
    while len(choices) < k:
        choice = random.choices(population, weights=weights, k=1)[0]
        choices.add(choice)
        # 确保同一元素不重复选择
        index = population.index(choice)
        population.pop(index)
        weights.pop(index)
    return list(choices)

my_list = [1, 2, 3, 4, 5]
weights = [10, 1, 1, 1, 1]
choices = weighted_sample(my_list.copy(), weights.copy(), 3)
print(choices)

使用累加权重

累加权重参数 (cum_weights) 在某些情况下是非常有用的,尤其是当你已经有累加权重数据或者累加权重的计算更为方便时。

示例

以下是一个使用累加权重的示例:

import random

elements = ['a', 'b', 'c', 'd']
cumulative_weights = [10, 30, 60, 100]

result = random.choices(elements, cum_weights=cumulative_weights, k=5)
print(result)

在这个例子中,如果你已经有了累加权重数据,可以直接使用它们进行随机选择,而不需要再转换为普通权重。

结论

累加权重参数的存在为 random.choices 提供了更多的灵活性和优化空间。当你已经有累加权重数据或者希望优化性能时,可以直接使用累加权重。而在其他情况下,你也可以使用普通权重,让 random.choices 自动计算累加权重。

综合示例

以下是一个综合示例,展示如何使用 random 模块的各种方法,包括带权重、不允许重复以及使用累加权重:

import random

# 生成随机数
print("Random float between 0.0 and 1.0:", random.random())
print("Random integer between 1 and 10:", random.randint(1, 10))
print("Random float between 1.0 and 10.0:", random.uniform(1.0, 10.0))

# 实现随机乱序
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print("Shuffled list:", my_list)

# 随机抽样
sample = random.sample(my_list, 2)
print("Random sample of 2 elements:", sample)

# 随机选择一个元素
choice = random.choice(my_list)
print("Random choice from list:", choice)

# 随机选择多个元素(允许重复)
choices = random.choices(my_list, k=3)
print("Random choices (3 elements):", choices)

# 随机选择多个元素(不允许重复)
choices = random.sample(my_list, 3)
print("Random sample (3 elements, no repeat):", choices)

# 随机选择一个元素,带权重
weights = [10, 1, 1, 1, 1]
choice = random.choices(my_list, weights=weights, k=1)
print("Weighted random choice from list:", choice)

# 随机选择多个元素,带权重(允许重复)
choices = random.choices(my_list, weights=weights, k=3)
print("Weighted random choices (3 elements):", choices)

# 随机选择多个元素,带权重(不允许重复)
choices = weighted_sample(my_list.copy(), weights.copy(), 3)
print("Weighted random sample (3 elements, no repeat):", choices)

# 使用累加权重
elements = ['a', 'b', 'c', 'd']
cumulative_weights = [10, 30, 60, 100]
result = random.choices(elements, cum_weights=cumulative_weights, k=5)
print("Random choices with cumulative weights:", result)

这些方法可以帮助你生成各种类型的随机数、打乱序列以及从序列中随机抽取元素。根据你的需求,选择合适的 random 方法可以使你的代码更具随机性和多样性。

短视频
每日一点 短视频 Python
License:  CC BY 4.0
Share

Further Reading

Nov 3, 2024

什么是 python 的闭包

在 Python 中,闭包(Closure)是一种函数对象,它不仅包含了函数的代码,还包含了函数创建时的环境变量。这意味着闭包可以“记住”其外部作用域中的变量,即使在外部作用域已经结束后,闭包仍然可以访问这些变量。 函数可以访问他被创建时所处的上下文环境,这被称为闭包。 闭包的基本特征 嵌套函数:闭

Nov 2, 2024

使用argparse模块解析命令行参数

在 Python 中,argparse 模块用于解析命令行参数,使得脚本可以更灵活地接受用户输入。以下是如何使用 argparse 模块解析命令行参数的详细介绍和示例。 基本用法 示例:简单的命令行参数解析 首先,创建一个简单的脚本来解析命令行参数。我们将创建一个脚本,该脚本接受两个整数并打印它们的

Nov 1, 2024

Python中的二维码生成与解析(花里胡哨)

如何使用 qrcode 库生成各种有趣的二维码,包括彩色二维码、带 Logo 的二维码和动态 GIF 二维码。下面,我们将逐步介绍这些功能。 Qrcode 库简介 qrcode 库是一个强大的 Python 工具,用于生成二维码。除了基本的二维码,它还支持自定义功能,如颜色变化、样式设计和动画效果。

OLDER

Python中的zip函数,我想同时遍历几个列表怎么办?

NEWER

Python中的断言(assert)与异常处理(raise)

Recently Updated

  • 什么是 python 的闭包
  • 使用argparse模块解析命令行参数
  • Python中的二维码生成与解析(花里胡哨)
  • Python中的二维码生成与解析(基础使用)
  • 使用platform模块获取系统信息

Trending Tags

学习 Git 工具 SQL docker-compose 每日一点 快捷键 Flink fastapi Windows

Contents

©2025 RWO.cc. Some rights reserved.

Using the Halo theme Chirpy