For example
X=[5,6,2,3,1]
Y=[7,2,3,4,6]
I sort X:
X=[1,2,3,5,6]
But I want the same relative sort applied to Y so the numbers stay in the same positions relative to each other as before:
Y=[6,3,4,7,2]
I hope this makes sense!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Usually, you do a
zip–sort–unzipfor thisNow sort them together:
Pair that with a “unzip” (
zip(*...))which you could unpack:
Now you have
tupleinstead oflistobjects, but if you really need to, you can convert it back.As pointed out in the comments, this does introduce a very slight dependence on the second list in the sort: Consider the lists:
With my “recipe” above, at the end of the day, you’ll get:
which might be unexpected. To fix that, you could pass a
keyargument tosorted:Demo: