Ordering a second list according to the ordering of the first list

Asked

Viewed 1,707 times

4

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] in accordance with lista[0]. To illustrate what I want below:

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

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)]

Discontent the print(tuplas) to see the result.

Then I order for the second value:

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

Finally, I mount the second list again, iterating on the index of tuples:

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)
  • That way I get lista_ordenada = [[2, 3, 4, 6, 7], [3, 4, 4, 6, 8]]. What I want is for each list element[0][i] to be associated with the list element[1][i], so that when I sort list[0] this correspondence is maintained.

  • Rectifying: if you order list[0], you need to sort list[1] the same way. That’s right?

  • I just want to sort list[0] in ascending order. The first element of the output will be list_sorted[0][0]=2, as the smallest list element[0] is list[0][3]=2. As a list[1][3]=4, the ordered list_element[1][0]=4 the output should be list_ordered=[[2,...],[4,...]]. I don’t know if it’s clear...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.