Random Python dictionary key, weighted by values

后端 未结 9 2137
遥遥无期
遥遥无期 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:12

    Without constructing a new, possibly big list with repeated values:

    def select_weighted(d):
       offset = random.randint(0, sum(d.itervalues())-1)
       for k, v in d.iteritems():
          if offset < v:
             return k
          offset -= v
    

提交回复
热议问题