Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

701
Vistas
How to sort a python list, based on different indices?

For instance, we have a list of list. The list should be reverse sorted based on some index i, and if there is tie, they should be sorted in ascending or descending order based on the condition.

For eg:

The list is [['A', 2, 4.2], ['B', 4, 4.5], ['C', 2, 3.3], ['D', 2, 3.5]]

How to sort this so that the result is:

  • [['B', 4, 4.5], ['A', 2, 4.2], ['D', 2, 3.5], ['C', 2, 3.3]]
  • [['B', 4, 4.5], ['C', 2, 3.3], ['D', 2, 3.5], ['A', 2, 4.2]]

In first condition, i want them to be sorted in descending order based on index 1, and then again on descending order on index 2 if there is tie on index 1.

In second condition, i want them to be sorted in descending order based on index 1, and then in ascending order on index 2 if there is tie on index 1.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

What I can think of is what follows:

myList = [['A', 2, 4.2], ['B', 4, 4.5], ['C', 2, 3.3], ['D', 2, 3.5]]
print(sorted(myList, key= lambda x: (x[1], x[2]), reverse=True))
print(sorted(myList, key= lambda x: (x[1], -1*x[2]), reverse=True))

Output

[['B', 4, 4.5], ['A', 2, 4.2], ['D', 2, 3.5], ['C', 2, 3.3]]
[['B', 4, 4.5], ['C', 2, 3.3], ['D', 2, 3.5], ['A', 2, 4.2]]

Explnatation

sorted function takes two arguments: an iterable, which can be a list, set, or anything that is iterable, and a key, which defines the pattern of sorting. In the key argument, I have defined a tuple ((x[1], x[2])) that indicates the order of sorting, if the element with index 1 is tied, then it goes to check index number 2. The second sorted function is the same, but when it goes to the element with index number 2, it checks its negative value to sort them in ascending order.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda