A weighted version of random.choice

后端 未结 25 1877
闹比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:49

    If you happen to have Python 3, and are afraid of installing numpy or writing your own loops, you could do:

    import itertools, bisect, random
    
    def weighted_choice(choices):
       weights = list(zip(*choices))[1]
       return choices[bisect.bisect(list(itertools.accumulate(weights)),
                                    random.uniform(0, sum(weights)))][0]
    

    Because you can build anything out of a bag of plumbing adaptors! Although... I must admit that Ned's answer, while slightly longer, is easier to understand.

提交回复
热议问题