There is a list:
a = [("ax", 1), ("ec", 3), ("bk", 5)]
another list:
b = ["ec", "ax", "bk"]
I want to sort a according to b:
sort_it(a, b)
a = [("ec", 3), ("ax", 1), ("bk", 5)]
How to do this?
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.
This sorts
ain-place using the the index inbof the first element of each tuple fromaas the values it sorts on.Another, possibly cleaner, way of writing it would be:
If you had large numbers of items, it might be more efficient to do things a bit differently, because
.index()can be an expensive operation on a long list, and you don’t actually need to do a full sorting since you already know the order:Note that this will only work for a list of 2-tuples. If you want it to work for arbitrary-length tuples, you’d need to modify it slightly: