随机 Python 字典键,按值加权 [英] Random Python dictionary key, weighted by values

查看:23
本文介绍了随机 Python 字典键,按值加权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中每个键都有一个可变长度的列表,例如:

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

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

有没有一种干净的方法来获取随机字典键,按其值的长度加权?random.choice(d.keys()) 将平均加权密钥,但在上述情况下,我希望 'a' 大约有一半的时间返回.

Is there a clean way to get a random dictionary key, weighted by the length of its value? random.choice(d.keys()) will weight the keys equally, but in the case above I want 'a' to be returned roughly half the time.

推荐答案

这行得通:

random.choice([k for k in d for x in d[k]])

这篇关于随机 Python 字典键,按值加权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆