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

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

    You can do this rather easily by using itertools.islice to get the Nth item of an iterable:

    >>> import random
    >>> import itertools
    >>> import collections
    >>> c = collections.Counter({'a': 2, 'b': 1})
    >>> i = random.randrange(sum(c.values()))
    >>> next(itertools.islice(c.elements(), i, None))
    'a'
    

提交回复
热议问题