Fastest way to rank items with multiple values and weightings

后端 未结 2 1862
独厮守ぢ
独厮守ぢ 2021-01-29 07:16

I have a collection of key value pairs like this:

{ 
   \'key1\': [value1_1, value2_1, value3_1, ...], 
   \'key2\': [value1_2, value2_2, value3_2, ...],
   ...
         


        
2条回答
  •  情深已故
    2021-01-29 07:37

    Here's a normalization function, that will linearly transform your values into [0,1]

    def normalize(val, ilow, ihigh, olow, ohigh):
        return ((val-ilow) * (ohigh-olow) / (ihigh - ilow)) + olow
    

    Now, use normalize to compute a new dictionary with normalized values. Then, sort by the weighted sum:

    def sort(d, weights, ranges):
        # ranges is a list of tuples containing the lower and upper bounds of the corresponding value
    
        newD = {k:[normalize(v,ilow, ihigh, 0, 1) for v,(ilow, ihigh) in zip(vals, ranges)] for k,val in d.iteritems()}  # d.items() in python3
        return sorted(newD, key=lambda k: sum(v*w for v,w in zip(newD[k], weights)))
    

提交回复
热议问题