(Python) algorithm to randomly select a key based on proportionality/weight

前端 未结 6 1861
盖世英雄少女心
盖世英雄少女心 2020-12-09 06:33

I\'m a bit at a loss as to how to find a clean algorithm for doing the following:

Suppose I have a dict k:

>>> k = {\'A\': 68, \'B\': 62, \'         


        
6条回答
  •  隐瞒了意图╮
    2020-12-09 07:15

    This should do the trick:

    >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81}
    >>> import random
    >>> def weighted_pick(dic):
    ...     total = sum(dic.itervalues())
    ...     pick = random.randint(0, total-1)
    ...     tmp = 0
    ...     for key, weight in dic.iteritems():
    ...         tmp += weight
    ...         if pick < tmp:
    ...             return key
    

提交回复
热议问题