selection based on percentage weighting

后端 未结 13 2108
忘掉有多难
忘掉有多难 2020-12-04 13:40

I have a set of values, and an associated percentage for each:

a: 70% chance
b: 20% chance
c: 10% chance

I want to select a value (a, b, c) based

13条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 14:08

    today, the update of python document give an example to make a random.choice() with weighted probabilities:

    If the weights are small integer ratios, a simple technique is to build a sample population with repeats:

    >>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
    >>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
    >>> random.choice(population)
    'Green'
    

    A more general approach is to arrange the weights in a cumulative distribution with itertools.accumulate(), and then locate the random value with bisect.bisect():

    >>> choices, weights = zip(*weighted_choices)
    >>> cumdist = list(itertools.accumulate(weights))
    >>> x = random.random() * cumdist[-1]
    >>> choices[bisect.bisect(cumdist, x)]
    'Blue'
    

    one note: itertools.accumulate() needs python 3.2 or define it with the Equivalent.

提交回复
热议问题