How to do weighted random sample of categories in python

后端 未结 9 2151

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

    import numpy
    
    n = 1000
    pairs = [(.3, 'a'), (.3, 'b'), (.4, 'c')]
    probabilities = numpy.random.multinomial(n, zip(*pairs)[0])
    result = zip(probabilities, zip(*pairs)[1])
    # [(299, 'a'), (299, 'b'), (402, 'c')]
    [x[0] * x[1] for x in result]
    # ['aaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccc']
    

    How exactly would you like to receive the results?

提交回复
热议问题