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

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

    You could wrap the iterator in list() to convert it into a list for random.choice():

    nextthing = random.choice(list(scoreboard.elements()))
    

    The downside here is that this expands the list in memory, rather than accessing it item-by-item as would normally get with an iterator.

    If you wanted to solve this iteratively, this algorithm is probably a good choice.

提交回复
热议问题