A weighted version of random.choice

后端 未结 25 1924
闹比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:46

    One way is to randomize on the total of all the weights and then use the values as the limit points for each var. Here is a crude implementation as a generator.

    def rand_weighted(weights):
        """
        Generator which uses the weights to generate a
        weighted random values
        """
        sum_weights = sum(weights.values())
        cum_weights = {}
        current_weight = 0
        for key, value in sorted(weights.iteritems()):
            current_weight += value
            cum_weights[key] = current_weight
        while True:
            sel = int(random.uniform(0, 1) * sum_weights)
            for key, value in sorted(cum_weights.iteritems()):
                if sel < value:
                    break
            yield key
    

提交回复
热议问题