A weighted version of random.choice

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

    Using numpy

    def choice(items, weights):
        return items[np.argmin((np.cumsum(weights) / sum(weights)) < np.random.rand())]
    

提交回复
热议问题