如何基于加权概率从python字典中选择键? [英] How to choose keys from a python dictionary based on weighted probability?

查看:90
本文介绍了如何基于加权概率从python字典中选择键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python字典,其中的键代表某些项目,值代表该项目的某些(标准化)权重.例如:

I have a Python dictionary where keys represent some item and values represent some (normalized) weighting for said item. For example:

d = {'a': 0.0625, 'c': 0.625, 'b': 0.3125}
# Note that sum([v for k,v in d.iteritems()]) == 1 for all `d`

鉴于项目与权重之间的这种相关性,我如何从d中选择一个键,使得结果的6.25%的时间为'a',结果的32.25%的时间为'b',以及62.5%的时间结果是"c"?

Given this correlation of items to weights, how can I choose a key from d such that 6.25% of the time the result is 'a', 32.25% of the time the result is 'b', and 62.5% of the result is 'c'?

推荐答案

def weighted_random_by_dct(dct):
    rand_val = random.random()
    total = 0
    for k, v in dct.items():
        total += v
        if rand_val <= total:
            return k
    assert False, 'unreachable'

应该做到这一点.仔细检查每个密钥并保持连续的总和,如果随机值(介于0和1之间)落在插槽中,它将返回该密钥

Should do the trick. Goes through each key and keeps a running sum and if the random value (between 0 and 1) falls in the slot it returns that key

这篇关于如何基于加权概率从python字典中选择键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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