Random Python dictionary key, weighted by values

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

    I'd say this:

    random.choice("".join([k * len(d[k]) for k in d]))
    

    This makes it clear that each k in d gets as many chances as the length of its value. Of course, it is relying on dictionary keys of length 1 that are characters....


    Much later:

    table = "".join([key * len(value) for key, value in d.iteritems()])
    random.choice(table)
    

提交回复
热议问题