random.choices with weighted options output

后端 未结 2 1339
孤街浪徒
孤街浪徒 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] ) )  
    

提交回复
热议问题