A weighted version of random.choice

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

    If you don't mind using numpy, you can use numpy.random.choice.

    For example:

    import numpy
    
    items  = [["item1", 0.2], ["item2", 0.3], ["item3", 0.45], ["item4", 0.05]
    elems = [i[0] for i in items]
    probs = [i[1] for i in items]
    
    trials = 1000
    results = [0] * len(items)
    for i in range(trials):
        res = numpy.random.choice(items, p=probs)  #This is where the item is selected!
        results[items.index(res)] += 1
    results = [r / float(trials) for r in results]
    print "item\texpected\tactual"
    for i in range(len(probs)):
        print "%s\t%0.4f\t%0.4f" % (items[i], probs[i], results[i])
    

    If you know how many selections you need to make in advance, you can do it without a loop like this:

    numpy.random.choice(items, trials, p=probs)
    

提交回复
热议问题