随机Python字典键,由值加权 [英] Random Python dictionary key, weighted by values
本文介绍了随机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屋!
查看全文