python简单的加权随机数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/comprel/article/details/72843289

随机访问list资源,但资源访问有一个权重。建立wightlist 权重列表,表示对应的资源编号的权重值,依据权重值生成重读个资源,加入到wlatch 链表中,然后就可用依据random随机生成数字来实现加权的随机,权重越大,则资源个数越多,则随机访问到的概率也就变大。

示例如下:


#coding=utf8

import random
import time

list = {
    1: "test1",
    2: "test2",
    3: "test3",
    4: "test4",
    5: "test5"
}

wlatch = []
num = 0
wightlist = {1: 2, 2: 1, 3: 3, 4: 1, 5: 3}
for i in wightlist:
    for x in range(wightlist[i]):
        wlatch.append(i)
        num += 1

print wightlist
print num
print wlatch
while 1:
   radnum=random.randint(0,num-1)
   print list[wlatch[radnum]]
   time.sleep(1)

输出:

{1: 2, 2: 1, 3: 3, 4: 1, 5: 3}
10
[1, 1, 2, 3, 3, 3, 4, 5, 5, 5]
test3
test3
test5
test5
test2
test1

猜你喜欢

转载自blog.csdn.net/comprel/article/details/72843289
今日推荐