Python-- 有权重的随机选择, Weighted Random Choice

import random

def windex(lst):
    '''an attempt to make a random.choose() function that makes weighted choices
    accepts a list of tuples with the item and probability as a pair'''
    wtotal = sum([x[1] for x in lst])
    n = random.uniform(0, wtotal)
    for item, weight in lst:
        if n < weight:
            break
        n = n - weight
    return item

你可能感兴趣的:(Python-- 有权重的随机选择, Weighted Random Choice)