Sorting a second list according to the sorting of the first list

3

I have the following (silly example):

lista=[[3,6,4,2,7],[8,4,6,4,3]]

I want to put lista[0] in ascending order, modifying lista[1] according to lista[0] . To illustrate what I want below:

lista_ordenada=[[2,3,4,6,7],[4,8,6,4,3]]
    
asked by anonymous 02.10.2015 / 21:51

1 answer

1

If I understand, this is what you want:

primeira_lista = lista[0]
segunda_lista = lista[1]
tuplas = [(indice, valor) for indice, valor in enumerate(primeira_lista)]
# print(tuplas)
tuplas.sort(key=lambda x: x[1])
# print(tuplas)
resultado = []
for indice, valor in tuplas:
    resultado.append(segunda_lista[indice])
print(resultado)

Here I am creating a list of tuples, preserving the original index of the first list:

tuplas = [(indice, valor) for indice, valor in enumerate(primeira_lista)]

Uncomment the print(tuplas) to see the result.

Then I sort by the second value:

tuplas.sort(key=lambda x: x[1])

Finally, I add the second list again, iterating over the tuples' indexes:

resultado = []
for indice, valor in tuplas:
    resultado.append(segunda_lista[indice])

The first list can be ordered using simply:

primeira_lista_ordenada = sorted(primeira_lista)
    
02.10.2015 / 21:54