Weighted choice in python

Works in 3.6+

random.choices([1,2], weights=[0.001, 0.8], k=1)[0]

Here is proof that makes 100k choices from [1,2] array and then counts numbers:

arr = [ch[0] for ch in [random.choices([1,2], weights=[0.001, 0.8], k=1) for _ in range(100000)]]
>>> arr.count(1), arr.count(2)
(114, 99886)
#python #statistics
7
Ivan Borshchov profile picture
Nov 01, 2017
by Ivan Borshchov
Did it help you?
Yes !
No

Best related