具有概率的Python随机列表索引

时间:2016-05-17 01:08:08

标签: python

如何编写一个函数,它给出了list-element的随机索引,但是基于列表中的概率?

列表看起来像5个元素。

a = [0.1, 0.2, 0.4, 0.2, 0.1]

有一个简单而快速的解决方案吗?感谢

2 个答案:

答案 0 :(得分:4)

这听起来像是Numpy's numpy.random.choice()的作业及其p参数:

p : 1-D array-like, optional

The probabilities associated with each entry in a. If not given,
the sample assumes a uniform distribtion over all entries in a.

因此,如果只有一个列表(其中一个元素既是每个元素的概率,又是元素本身的选择,你可以这样做:

from numpy.random import choice

elementsAndProbabilities = [0.1, 0.2, 0.4, 0.2, 0.1]

randomElement = choice(elementsAndProbabilities, p=elementsAndProbabilities)
print randomElement

如果您有一个元素列表和每个元素的概率列表(单独),您可以这样做:

from numpy.random import choice

elements = ["first", "second", "third", "fourth", "fifth"]
probabilities = [0.1, 0.2, 0.4, 0.2, 0.1]    

randomElement = choice(elements, p=probabilities)
print randomElement

现在,你说你想要索引,而不是元素,所以我们可以得到这样的索引:

from numpy.random import choice

probabilities = [0.1, 0.2, 0.4, 0.2, 0.1]

randomElement = choice(range(len(probabilities)), p=probabilities)
print randomElement

答案 1 :(得分:2)

NumPy可能会更快,如果你拥有它,但如果没有,这里是一个纯Python解决方案。

from random import random

a = [0.1, 0.2, 0.4, 0.2, 0.1]

def randombin(bins):
    r = random()
    p = 0
    for i, v in enumerate(bins):
        p += v
        if r < p:
           return i
    # p may not equal exactly 1.0 due to floating-point rounding errors
    # so if we get here, just try again (the errors are small, so this
    # should not happen very often).  You could also just put it in the
    # last bin or pick a bin at random, depending on your tolerance for
    # small biases
    return randombin(bins)

print randombin(a)