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

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

问题描述

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

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

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

解决方案

这将工作:

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


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 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.

解决方案

This would work:

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

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

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