Python random 模块中的 random.choices() 方法用于从具有可选权重或累积权重的序列(如列表)中选择元素。当您想从列表中随机选择元素,但想要根据元素的权重控制每个元素被选中的可能性时,此方法特别有用。
此方法可以灵活地为序列中的每个元素指定权重。这些权重会影响选择每个元素的概率。更有可能选择权重较高的元素。此外,您还可以指定累积权重,而不是提供单个权重。累积权重是列表中每个元素的权重之和。
语法
以下是 random.choices() 方法的语法 -
random.choices(seq, weights=None, *, cum_weights=None, k=1)
参数
以下是此方法的参数 -
- seq:Sequence 数据类型(可以是列表、元组、字符串或集)。
- weights:一个可选列表,用于指定选择每个元素的可能性。值越高,概率越高。
- cum_weights: 累积权重的可选列表。这些是每个元素的权重和,当使用 itertools.accumulate() 计算时,可以优化选择。
- k:要从总体中选择的元素数。
返回值
此方法返回一个列表,其中包含从指定序列中随机选择的 k 个元素。
示例 1
下面是一个演示 python random.choices() 方法使用的基本示例 -
import random
# Population of items
input_list = ["Italy","Germany","London","Bristol"]
# Select 3 items with equal probability
selected_items = random.choices(input_list, k=6)
print(selected_items)
在执行上述代码时,我们得到以下输出 -
['London', 'London', 'Italy', 'Bristol', 'Italy', 'London']
示例 2
此示例使用带有权重的 python random.choices() 方法。
import random
input_list=["Italy","Germany","London","Bristol"]
output_list=random.choices(input_list,weights=[10,5,6,2],k=10)
print(output_list)
以下是代码的输出 -
['Bristol', 'London', 'Italy', 'London', 'London', 'Italy', 'Germany', 'Italy', 'Italy', 'Italy']
示例 3
让我们看看这种方法的另一个示例,其中包含累积权重 -
import random
from itertools import accumulate
# Population of items
input_list = ["Italy","Germany","London","Bristol"]
weights = [10, 5, 30, 10]
cum_weights = list(accumulate(weights))
# Select 4 items based on cumulative weights
selected_items = random.choices(input_list, cum_weights=cum_weights, k=8)
print(selected_items)
以下是代码的输出 -
['Italy', 'London', 'London', 'London', 'Bristol', 'Italy', 'Bristol', 'London']