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

前端 未结 6 1844
盖世英雄少女心
盖世英雄少女心 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:14

    The simplest way of doing this when your weights are relatively small integers (such as in your example) is to build a long string containing all the characters in the appropriate weights and choose a character at random from it:

    import random
    d = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81}
    s = ''.join(k*v for k,v in d.items())
    random.choice(s)
    

    Note though that this method will use quite a lot of memory if your weights are large, in which case you might prefer a different solution.

提交回复
热议问题