Skip to main content
 首页 » 编程设计

python之给定总和为 1 的权重字典之如何使用随机选择加权键

2025年05月04日15zhengyun_ustc

我有一本看起来像这样的字典。

mychoice = {0.7: 2, 0.2: 1, 0.1:3} 

我将使用以下内容来选择要使用的值。在上面,70% 的时间选择值 2,20% 的时间选择值 1,10% 的时间选择值 3。

使用以下生成 0 到 1 之间的随机数并随机选择要使用的值的最佳方法是什么?

from random import random 
ran = random() 
if ran>.10 and <.30 then select value 1 with a key of .20 

谢谢

请您参考如下方法:

以您的示例为例,进行一些修改(在字典中交换键/值):

mychoice = {1: 0.2, 2: 0.7, 3:0.1} 
current = 0 
limits = {} 
 
for key in mychoice: 
    limits[key] = (current,current + mychoice[key]) 
    current = current + mychoice[key] #Next range should start at the end of current 
 
#This should give a new dictionary: {1:(0,0.2),2:(0.2,0.9),3;(0.9,1)} 
 
r = random.random() # float between 0 and 1 
 
for key in limits: 
    range = limits[key] 
    if r >= range[0] and r < range[1]: 
          return key 
return None 

这可以优化,但您明白了。