Python Forum

Full Version: Use ranking function for different lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi.

I have a function that i use to rank a list from highest to lowest, right now it is hard coded to one list, what i would like to be able to do is pass lists to it.


def rank():
    global mons
    dict = {}
    for i, e in enumerate(mons):                   
        dict[e] = i                                
    rank = 1                                      
    for key in sorted(dict.keys(), reverse=TRUE):
        mons[dict.get(key)] = rank                 
        rank = rank + 1       
renamed dict to thedict, otherwise you will be redefining python's dict

def rank(mons):
    thedict = {}
    for i, e in enumerate(mons):                   
        thedict[e] = i                                
    rank = 1                                      
    for key in sorted(thedict.keys(), reverse=True):
        mons[thedict.get(key)] = rank                 
        rank = rank + 1  
    return thedict
  
print(rank(['1','6','4','3','1']))
Output:
{'1': 4, '6': 1, '4': 2, '3': 3}
Sure i can do that, but that dooesn't solve my issue.
(Feb-15-2022, 12:30 PM)klatlap Wrote: [ -> ]Sure i can do that, but that dooesn't solve my issue.

It's unclear what issue you are trying to solve. For starters - what you are trying to accomplish? What rank functions should do?
I wanted to have this as a function that i could call and use on different lists, maybe i am unable to do that and will just have to reuse this code for each list.
What is wrong with Larz60's example? It does the same thing as yours, but you pass the list as an argument instead of it being hard coded. One ranker that can be used with any list.

I modified it a little to rank numbers instead of strings, and to return a list of "rankings".
def rank(values):
    valuemap = {value:index for index, value in enumerate(values)}
    result = [0] * len(values)
    for rank, value in enumerate(sorted(values, reverse=True)):
        result[valuemap[value]] = rank+1
    return result

print(rank([2, 5, 3, 6, 1, 4]))
Output:
[5, 2, 4, 1, 6, 3]
A problem with this is any duplicate values are removed because they are used as keys in the valuemap dictionary. But if this is what you want, numpy.argsort() does the same thing without the unique value requirement.
import numpy

values = ['1','6','4','3','1']
indices = numpy.argsort(values)
print(indices)
print([values[index] for index in indices])
Output:
[0 4 3 2 1] ['1', '1', '3', '4', '6']
Sorry guys, i think it was my misunderstanding, thanks for all your help, cheers laz