A weighted version of random.choice

后端 未结 25 1870
闹比i
闹比i 2020-11-21 06:29

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:



        
25条回答
  •  别跟我提以往
    2020-11-21 06:51

    I needed to do something like this really fast really simple, from searching for ideas i finally built this template. The idea is receive the weighted values in a form of a json from the api, which here is simulated by the dict.

    Then translate it into a list in which each value repeats proportionally to it's weight, and just use random.choice to select a value from the list.

    I tried it running with 10, 100 and 1000 iterations. The distribution seems pretty solid.

    def weighted_choice(weighted_dict):
        """Input example: dict(apples=60, oranges=30, pineapples=10)"""
        weight_list = []
        for key in weighted_dict.keys():
            weight_list += [key] * weighted_dict[key]
        return random.choice(weight_list)
    

提交回复
热议问题