Weighted choice short and simple

numpy, python

Solution

Since numpy version 1.7 you can use `numpy.random.choice()`:

elements = ['one', 'two', 'three'] 
weights = [0.2, 0.3, 0.5]

from numpy.random import choice
print(choice(elements, p=weights))

Problem

If I have a collection of items in a list. I want to choose from that list according to another list of weights. For example my collection is `['one', 'two', 'three']` and the weights are `[0.2, 0.3, 0.5]`, the I would expect the method to give me 'three' in about half of all draws. What is the easiest way to do so ?

Original source

Related problems