0

How do you sample from a list of probabilities that add up to 1 in python.

Ex. List: [0.1, 0.8, 0.1] The first element would be chosen 10% of the time, the second 80%, and the third 10%

Alex
  • 159
  • 3
  • 16

1 Answers1

0

Use the weights allowed by the random.choices function. For example:

import random

floats = [0.1, 0.8, 0.1]
weights = [0.1, 0.8, 0.1]
k = 1

choice = random.choices(population=floats, weights=weights, k=k)
print(choice)

It returns it as a list because you can have k equal the number of items you want to choose.

Evan Bloemer
  • 1,051
  • 2
  • 11
  • 31