【问题标题】:Python random list-index with probability [duplicate]具有概率的Python随机列表索引[重复]
【发布时间】:2016-09-12 22:18:28
【问题描述】:

如何编写一个函数,让我获得列表元素的随机索引,但基于列表中的概率?

列表看起来像这样,有 5 个元素。

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

有没有简单快速的解决方案?谢谢

【问题讨论】:

标签: python


【解决方案1】:

如果你有 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)

【讨论】:

    【解决方案2】:

    这听起来像是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
    

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

    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
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 2015-06-08
      • 2017-10-01
      • 2013-07-10
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多