How to do weighted random sample of categories in python

后端 未结 9 2139

Given a list of tuples where each tuple consists of a probability and an item I\'d like to sample an item according to its probability. For example, give the list [ (.3, \'a\'),

9条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 18:15

    This might do what you want:

    numpy.array([.3,.4,.3]).cumsum().searchsorted(numpy.random.sample(5))
    

提交回复
热议问题