1. 程式人生 > >Python-- 有權重的隨機選擇, Weighted Random Choice

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