Question:
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]]
Answer:
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)]
Discard the print(tuplas)
to see the result.
Then I sort by the second value:
tuplas.sort(key=lambda x: x[1])
Finally, I put together the second list again, iterating over the tuple indexes:
resultado = []
for indice, valor in tuplas:
resultado.append(segunda_lista[indice])
The first list can be sorted using simply:
primeira_lista_ordenada = sorted(primeira_lista)