Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Transforming a list of points in a "rank" of indexes

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!