import random
dict = {'red':0.010,'yellow':0.001,'green':0.9,'orange':0.089}
z={}
for i in range(0,99999):
x = random.uniform(0,1)
y = 0
for key in dict:
y += dict[key]
if y> x:
if key in z:
z[key]=z[key]+1
else:
z[key]=0
break
num = 0
c={}
for i in z:
num += z[i]
for i in z:
c[i]=z[i]/num
print (c)
* 1 random.unifrom的功能是随机产生一个浮点数
2 循环十万次用以验验证,验证结果如下,可知该方法正确
{'green': 0.8995249762488124, 'orange': 0.08969448472423622, 'yellow': 0.0010200510025501275, 'red': 0.00976048802440122}