random.choices with weighted options output

后端 未结 2 1340
孤街浪徒
孤街浪徒 2021-01-29 08:16
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

相关标签:
2条回答
  • 2021-01-29 08:31

    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] ) )  
    
    0 讨论(0)
  • 2021-01-29 08:35

    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().

    0 讨论(0)
提交回复
热议问题