Let's say that I have a list of points from a torunament
points = [0, 12, 9]
And I want to have a ranking of the players, so the expected outputs would be
[1, 2, 0]
Because the index 1 is first in the ranking, followed by index 2 and then index 0. My idea was to use a for to iterate through all the numbers, getting the biggest value, find the index of the biggest value and then assign the value in the ranking, but it seems unnecessary long and complicated. Any tips?
Use sorted:
points = [0, 12, 9]
res = sorted(range(len(points)), key=lambda x: points[x], reverse=True)
print(res)
Output
[1, 2, 0]
The idea is to sort the indexes of the list (range(3)) according to their value on the list, hence the key=lambda x: points[x]. The reverse True is because you want a descending ranking.
points = [0, 12, 9]
points_and_indices = [(p, i) for i, p in enumerate(points)]
points_and_indices.sort(reverse=True)
indices = [i for p, i in points_and_indices]
print(indices)
output:
[1, 2, 0]
UPDATE
You say in a comment
The first index who got that number of points is ahead
Unfortunately this causes the above solution to be wrong for your purposes, because the indices are included in the reverse sort.
To exploit the stability of Python sorts we must either not include the indices in the reverse sort, or use a decreasing function of the points instead of the points themselves.
We can sort according to the negative points, and also condense it all into a one-liner, like this:
points = [0, 12, 9, 12]
indices = [i for _, i in sorted((-p, i) for i, p in enumerate(points))]
print(indices)
output:
[1, 3, 2, 0]
Anyway, the solution by Dani Mesejo is more pythonic, even though the use of a sort key may cause some head scratching in people coming from other programming languages.