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

前端 未结 6 1563
天命终不由人
天命终不由人 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 09:02

    Another variant with iteration:

    import collections
    from collections import Counter
    import random
    
    
    class CounterElementsRandomAccess(collections.Sequence):
        def __init__(self, counter):
            self._counter = counter
    
        def __len__(self):
            return sum(self._counter.values())
    
        def __getitem__(self, item):
            for i, el in enumerate(self._counter.elements()):
                if i == item:
                    return el
    
    scoreboard = Counter('AAAASDFQWERQWEQWREAAAAABBBBCCDDVBSDF')
    score_elements = CounterElementsRandomAccess(scoreboard)
    for i in range(10):
        print random.choice(score_elements)
    

提交回复
热议问题