无重复但有概率的随机抽样

Random sample without repetition but probability

我不知何故缺少 python 中的一个函数,它是我知道的两个函数的组合。 我有这些数字和概率的列表,想从中选择 n 个,不重复。

random.sample 可以从列表中选择而不重复,但不允许概率:

l = [5,124,6,2,7,1]
sample(l,k=5)

另一方面,选择允许我使用权重,但使用重复:

choices(l,k=2,weights=[0.5,0.25,0.25,0.125,0,0.125])

有没有机会结合起来怎么做? 直到现在我 运行 一个 while 循环经常做选择,直到唯一选择的元素的数量变成 k。但这效率很低,尤其是一个元素的概率很大。

numpy.random.choice 有效。使用:

import numpy as np

l = [5,124,6,2,7,1]
weights=[0.5,0.25,0.25,0.125,0,0.125]
weights = [w/sum(weights) for w in weights]
np.random.choice(l, size=5, replace=False, p=weights)

编辑使概率总和为 1