-1

Hello I have a question related to the sort function in python. So if I have 2 arrays x and y e.g

X = [1, 5, 6, 2]
Y = [2, 7, 5, 1]

If i sort x, y wont be effected but what if i want it to like follow that index if that makes sense like e.g

>>> X
[1, 2, 5, 6]
>>> Y
[2, 1, 7, 5]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    You could merge them into a list of pairs e.g. `[(1,2), (5,7), (6,5), (2,1)]`. Then sort that list and then read off the second part of each pair. – Tom Dalton Feb 24 '21 at 16:57
  • to expand on Tom's suggestion: `[y for x, y in sorted(zip(X, Y))]` – Samwise Feb 24 '21 at 16:58

1 Answers1

1

You can sort the indices in range(len(X)) based on the values of X, then update X and Y accordingly:

>>> X = [1, 5, 6, 2]
>>> Y = [2, 7, 5, 1]
>>> Z = sorted(range(len(X)), key=lambda i: X[i])
>>> X, Y = map(list, zip(*((X[i], Y[i]) for i in Z)))
>>> X
[1, 2, 5, 6]
>>> Y
[2, 1, 7, 5]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55