This sounds like a job for Numpy's numpy.random.choice()
, and its p
parameter:
p : 1-D array-like, optional
The probabilities associated with each entry in a. If not given,
the sample assumes a uniform distribtion over all entries in a.
So if there's only one list (where an element is both the probability of each element, and the element itself to be selected, you can do it like this:
from numpy.random import choice
elementsAndProbabilities = [0.1, 0.2, 0.4, 0.2, 0.1]
randomElement = choice(elementsAndProbabilities, p=elementsAndProbabilities)
print randomElement
If you have a list of elements and a list of probabilities for each element (separate), you can do it like this:
from numpy.random import choice
elements = ["first", "second", "third", "fourth", "fifth"]
probabilities = [0.1, 0.2, 0.4, 0.2, 0.1]
randomElement = choice(elements, p=probabilities)
print randomElement
Now, you said you wanted the index, not the element, so we can get the index like this:
from numpy.random import choice
probabilities = [0.1, 0.2, 0.4, 0.2, 0.1]
randomElement = choice(range(len(probabilities)), p=probabilities)
print randomElement