繁体   English   中英

从Random.choices函数获取唯一项列表

[英]get a list of unique items from Random.choices function

我有一种使用随机包生成具有一定概率的列表的方法,例如:

import random

seed = 30
rand = random.Random(seed)
options_list = [1, 2, 3, 4, 5, 6]
prob_weights = [0.1, 0.2, 0.1, 0.05, 0.02, 0.06]
result = rand.choices(option_list, prob_weights, k=4) # k will be <= len(option_list)

我的问题是result可以容纳两个相同的项目,并且我希望它是唯一的。

我可以使k参数更大,然后过滤出唯一的项,但这似乎是错误的方法。 我查看了文档,但没有看到choices函数获得这种参数。

有什么想法如何配置random以返回唯一项列表?

. 您可以使用np.random.choice ,它允许您分配与每个条目相关的概率,还可以生成随机样本 但是,概率必须加起来为1,您必须将向量除以其L^1-Norm 因此,这是您可以执行的操作:

import numpy as np
options_list = np.array([1, 2, 3, 4, 5, 6])
prob_weights = np.array([0.1, 0.2, 0.1, 0.05, 0.02, 0.06])
prob_weights_scaled = prob_weights / sum(prob_weights)
some_length = 4 

np.random.choice(a=options_list, size=some_length, replace=False, p=prob_weights_scaled)

产量

array([2, 1, 6, 3])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM