Home > Enterprise >  Return list of indices sorted by their value and then position if tied
Return list of indices sorted by their value and then position if tied

Time:11-01

I'm facing this problem while learning python:

I coded a function that generates a list of scores based on input (where I use the index to refer to the players), for example:

scores = [5, 15, 0, 25, 20, 15]

I want to create a ranking list of the indices in descending order, and in case there are players with the same score, rank those by who has a lower index. For the example above I want this returned:

ranking = [3, 4, 1, 5, 0, 2]

My closest solution was to sort it and then get the index of each value like:

ranking = [ranking.index(x) for x in sorted(ranking, reverse=True)]

But this gets the index of the first x it meets so it returns

[3, 4, 1, 1, 0, 2]

ignoring the players with tied values. Is there a way to do this just in pure python? no libraries or anything.

CodePudding user response:

You can sort the list of indices using the values as a key:

sorted(range(len(scores)), key=scores.__getitem__, reverse=True)

Another way would be to sort the tuple of (rank, index) and extract the second element:

[x[1] for x in sorted((x[::-1] for x in enumerate(scores)), reverse=True)]

Both algorithms are more efficient than doing linear search for each element using index.

  • Related