Weighted choice short and simple [duplicate]

Solution 1:

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))

Solution 2:

Since Python 3.6, you can do weighted random choice (with replacement) using random.choices.

random.choices(population, weights=None, *, cum_weights=None, k=1)

Example usage:

import random
random.choices(['one', 'two', 'three'], [0.2, 0.3, 0.5], k=10)
# ['three', 'two', 'three', 'three', 'three',
#  'three', 'three', 'two', 'two', 'one']