import random
a = 1
b = 2
c = 3
print(random.choices([a,b,c], [50,3,1]))
The code above outputs [1], [2] or [3] can someone explain why the output has
random.choices draws a list of values that you can specify with k=..
when calling it:
fourty = random.choices(range(10),k=40)
You can print the single value you get by indexing into it using choices
method of specifying probabilities
print(random.choices([a,b,c], [50,3,1])) [0] # get the one single value from the result list
or you can use random.choice() providing an iterable that reflects your propabilites:
import random
a=1
b=2
c=3
# create an iterable that reflects your propabilies and draw 1 element from it
print(random.choice( [a]*50+[b]*3+[c] ) )
Because random.choices(population, weights=None, *, cum_weights=None, k=1) returns a list of k elements. In your case, since you didn't pass any value for k
, the list has only an item.
If you want to get a value, and not a list, you could use random.choice(seq), but in that case you could not pass a list of weights as with random.choices()
.