Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda