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

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

    The following will get a random item where the score is the weighting for how often to return that item.

    import random
    
    def get_random_item_weighted(scoreboard):    
        total_scoreboard_value = sum(scoreboard.values())
    
        item_loc = random.random() * total_scoreboard_value
        current_loc = 0
        for item, score in scoreboard.items():
            current_loc += score
            if current_loc > item_loc:
                return item
    

    for instance, if there are 2 items:

    item1 has a score 5
    item2 has a score 10

    item2 will be returned twice as often as item1

提交回复
热议问题