Random Python dictionary key, weighted by values

后端 未结 9 2124
遥遥无期
遥遥无期 2020-12-01 03:29

I have a dictionary where each key has a list of variable length, eg:

d = {
 \'a\': [1, 3, 2],
 \'b\': [6],
 \'c\': [0, 0]
}

Is there a cle

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 04:06

    Given that your dict fits in memory, the random.choice method should be reasonable. But assuming otherwise, the next technique is to use a list of increasing weights, and use bisect to find a randomly chosen weight.

    >>> import random, bisect
    >>> items, total = [], 0
    >>> for key, value in d.items():
            total += len(value)
            items.append((total, key))
    
    
    >>> items[bisect.bisect_left(items, (random.randint(1, total),))][1]
    'a'
    >>> items[bisect.bisect_left(items, (random.randint(1, total),))][1]
    'c'
    

提交回复
热议问题