0

Suppose I got to list X, Y of integers both size N. the vector Y, corresponding to the X , (the xi label is yi)

Now I want to sort X and then sort Y in same order if I done it in java I would override the sort method, but i am kind of new in python... any nice method to do so?

Saar BK
  • 13
  • 3
  • What does "(*) such as the label of xi is yi" mean? – kpie Feb 24 '22 at 17:25
  • We need sample input and output data in order to be able to understand your problem. You also seem to have forgotten to post the code that's troubling you – DarkKnight Feb 24 '22 at 17:28
  • You can override the sort function with the key argument. Have a look at: https://stackoverflow.com/questions/2531952/how-to-use-a-custom-comparison-function-in-python-3 – Kavli Feb 24 '22 at 17:28

2 Answers2

0

Not sure if this is what you mean by "nice":

combo = sorted(zip(x,y))

sorted_x = [a for a,b in combo]
sorted_y = [b for a,b in combo]
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Use zip() to bind each data point in X with its associated data point in Y. Then use sorted() and a list comprehension to read off the result:

x = [3, 1, 2]
y = [5, 4, 6]

# Prints [4, 6, 5]
# These values are sorted in ascending order of corresponding x-value:
# 1 --> 4
# 2 --> 6
# 3 --> 5
result = [y_data for _, y_data in sorted(zip(x, y))]

print(result)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33