How to do weighted random sample of categories in python

后端 未结 9 2233

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:31

    Since nobody used the numpy.random.choice function, here's one that will generate what you need in a single, compact line:

    numpy.random.choice(['a','b','c'], size = 20, p = [0.3,0.4,0.3])
    

提交回复
热议问题