How can I get a weighted random pick from Python's Counter class?

前端 未结 6 1566
天命终不由人
天命终不由人 2021-02-07 08:16

I have a program where I\'m keeping track of the success of various things using collections.Counter — each success of a thing increments the corr

6条回答
  •  攒了一身酷
    2021-02-07 08:49

    Another variant, Setup is a bit cumbersome, but lookup is in logarithmic complexity (suitable when several lookups are needed):

    import itertools
    import random
    from collections import Counter
    from bisect import bisect
    
    counter = Counter({"a": 5, "b": 1, "c": 1})
    
    #setup
    most_common = counter.most_common()
    accumulated = list(itertools.accumulate([x[1] for x in most_common])) # i.e. [5, 6, 7]
    total_size = accumulated[-1]
    
    # lookup
    i = random.randrange(total_size)
    print(most_common[bisect(accumulated, i)])
    

提交回复
热议问题