An alternative is to create a list of indices, and sort these indices according to their value in x
.
Then you use these indexes to sort the lists:
x = [7, 5, 9, 4, 2, 3, 8, 1, 6, 10]
y = ['sete', 'cinco', 'nove', 'quatro', 'dois', 'tres', 'oito', 'um', 'seis', 'dez']
# ordene os índices em vez dos elementos em si
indices = list(range(len(x)))
indices.sort(key=lambda i: x[i]) # ordene os índices com relação ao seu respectivo valor em x
# crie as listas baseado na ordem dos índices
new_x = [x[i] for i in indices]
new_y = [y[i] for i in indices]
print(new_x) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(new_y) # ['um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez']
list(range(len(x)))
creates the list with the indexes (in this case, the numbers from zero to the size of x
).
Next, we order the indexes, using as a criterion the respective value in the list x
. After the sort
, the list indices
will be [7, 4, 5, 3, 1, 8, 0, 6, 2, 9]
, which means that x[7]
is the first element of x
(when this is ordained), x[4]
is the second, etc., and the same goes for y
.
So just put the lists x
and y
in the order indicated by the list indices
.
Another way to create the already ordered index list would be:
indices = sorted(range(len(x)), key=lambda i: x[i])
On your list
x
is missing the number 6, but by the description of the problem, I believe it was typo...– hkotsubo