这行得通:
import random
def weighted_choice(weights):
choice = random.random() * sum(weights)
for i, w in enumerate(weights):
choice -= w
if choice < 0:
return i
weighted_choice([.3, .5, .2]) # returns 0,1,2 in proportion to the weight
测试它:
import collections
c = collections.Counter()
n = 1000000
for i in range(n):
c[weighted_choice([.3, .5, .2])] += 1
for k, v in c.items():
print '{}: {:.2%}'.format(k,float(v)/n)
打印:
0: 30.11%
1: 50.08%
2: 19.81%
优点,除了相当快,1)列表元素加起来不需要1或100,2)更多选择,只需向列表中添加更多元素:
for i in range(n):
c[weighted_choice([.3,.35,.1,.1,.15,.4])]+=1
打印:
0: 21.61%
1: 25.18%
2: 7.22%
3: 7.03%
4: 10.57%
5: 28.38%
(根据接受的答案计时,大约快 2 倍...)