A weighted version of random.choice

后端 未结 25 2390
闹比i
闹比i 2020-11-21 06:29

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:



        
25条回答
  •  耶瑟儿~
    2020-11-21 06:51

    If you have a weighted dictionary instead of a list you can write this

    items = { "a": 10, "b": 5, "c": 1 } 
    random.choice([k for k in items for dummy in range(items[k])])
    

    Note that [k for k in items for dummy in range(items[k])] produces this list ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'b', 'b', 'b', 'b', 'b']

提交回复
热议问题