Python:选择具有相关概率的数字 [英] Python: Selecting numbers with associated probabilities

查看:194
本文介绍了Python:选择具有相关概率的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
随机加权选择
生成具有给定(数字)分布的随机数

Possible Duplicates:
Random weighted choice
Generate random numbers with a given (numerical) distribution

我有一个列表列表,其中包含一系列数字以及相关的概率.

I have a list of list which contains a series on numbers and there associated probabilities.

prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]

例如,在prob_list[0]中,数字1的概率为0.5.因此,您希望1显示50%的时间.

for example in prob_list[0] the number 1 has a probability of 0.5 associated with it. So you would expect 1 to show up 50% of the time.

选择数字时如何增加数字的重量?

How do I add weight to the numbers when I select them?

注意:列表中的数字数量可以在6-100之间变化

NOTE: the amount of numbers in the list can vary from 6 - 100

编辑

在列表中,我有6个数字及其关联的概率.我想根据它们的概率选择两个数字.

In the list I have 6 numbers with their associated probabilities. I want to select two numbers based on their probability.

不能选择两次号码.如果选择"2",则无法再次选择.

No number can be selected twice. If "2" is selected it can not be selected again.

推荐答案

这可能就是您想要的.在中生成解决方案的扩展.从分布中删除所选项目,更新概率并返回selected item, updated distribution.尚未证明行得通,但应该给这个想法一个好印象.

This might be what you're looking for. Extension to a solution in Generate random numbers with a given (numerical) distribution. Removes the selected item from the distribution, updates the probabilities and returns selected item, updated distribution. Not proven to work, but should give a good impression of the idea.

def random_distr(l):
    assert l # don't accept empty lists
    r = random.uniform(0, 1)
    s = 0
    for i in xrange(len(l)):
        item, prob = l[i]
        s += prob
        if s >= r:
            l.pop(i) # remove the item from the distribution
            break
    else: # Might occur because of floating point inaccuracies
        l.pop()
    # update probabilities based on new domain
    d = 1 - prob 
    for i in xrange(len(l)):
        l[i][1] /= d
    return item, l

dist = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
while dist:
    val, dist = random_distr(dist)
    print val

这篇关于Python:选择具有相关概率的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆