samedi 20 février 2021

How can I make a python function that returns a random number using the objects in a list as probability weights? [duplicate]

Let's say I have a list [0.25,0.25,0.25,0.25]. I want to input this to a function which yields a random number between 0 and 3 with 25 percent of each number.

Something that yields the same as this but takes the form random([0.25,0.25,0.25,0.25])

import random
my_list = ['0'] * 0.25 + ['1'] * 0.25 + ['2'] * 0.25 + ['3'] * 0.25
random.choice(my_list)

Another example is random([0.1, 0.9])

which yields a 10 percent chance of printing '0' and a 90 percent chance of printing '1'

So essentially a general function random(list), which selects a random number between 0 and len(list) - 1 with probability weights being the objects in list




Aucun commentaire:

Enregistrer un commentaire