random.choices
是Python 3中random模块中的一个函数,用于从指定的序列中以指定的权重随机选择元素。下面我将对该函数进行详细介绍,并提供一些示例代码和注意事项。
random.choices(population, weights=None, *, cum_weights=None, k=1)
population
:指定要从中进行随机选择的序列,可以是列表、元组、字符串或其他可迭代对象。weights
(可选):指定每个元素的权重列表,列表中的每个值必须是非负数。如果未提供此参数,则每个元素的权重被假定为相等,即等概率选择。cum_weights
(可选):类似于weights
,但是是累积权重列表,即每个元素的权重是从序列开头到该元素位置的累积和。如果提供了cum_weights
,则weights
参数会被忽略。k
:指定要选择的元素数量,即随机选择的样本数。默认值为1,即选择一个元素。population
为空,则会引发IndexError
异常。weights
和cum_weights
同时提供,则会引发ValueError
异常。weights
或cum_weights
中包含负数,则会引发ValueError
异常。cum_weights
,则其长度必须与population
的长度相同。import random
# 例子1:等概率选择
population = ['A', 'B', 'C', 'D', 'E']
choices = random.choices(population, k=3)
print("例子1结果:", choices)
# 例子2:使用权重进行选择
weights = [1, 2, 3, 4, 5]
choices_weighted = random.choices(population, weights=weights, k=3)
print("例子2结果:", choices_weighted)
# 例子3:使用累积权重进行选择
cum_weights = [1, 3, 6, 10, 15] # 累积权重,相当于[1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5]
choices_cum_weighted = random.choices(population, cum_weights=cum_weights, k=3)
print("例子3结果:", choices_cum_weighted)