Home > OS >  Python Choice, get / return selected Wieght value
Python Choice, get / return selected Wieght value

Time:12-15

I use .Choices to select a value randomly whith weight value.

Is it possible to store the used weight value to a variable?

var = random.choices(population=A, B, C, weights=[20, 20, 60])

Thanks!

CodePudding user response:

Just store it before you give it to the function. You must also change the way you assign the population. Your Code sould look more like this:

my_weights = [20, 20, 60]
my_population = ["A", "B", "C"]
var = random.choices(population = my_population, weights = my_weights)

Like this the code should ork an you could access the weights and population afterwards in my_weights and my_population.

If you want to access the chosen weight, you can do it like this:

chosen_weight = [weight for i, weight in enumerate(my_weights) if my_population[i] in var]

CodePudding user response:

You just need a way to attach the weight to your choice. For that, a dataclass would work well.

from random import choices
from dataclasses import dataclass

@dataclass
class Choice:
    value: int
    weight: int

a = Choice(value=3, weight=20)
b = Choice(value=4, weight=20)
c = Choice(value=5, weight=60)

all_choices = choices(population=(a, b, c), weights=[a.weight, b.weight, c.weight])
first_choice = all_choices[0]
print(first_choice.value, first_choice.weight)

CodePudding user response:

You can store it before using and then just pass the variable to the weights argument

myweights = [20, 20, 60]
var = random.choices(population=[A, B, C], weights=myweights)

However random.choices() only returns a list of elements chosen from the population, so you can't get the weights after.

  • Related