Reputation: 295
I have two list with the same items in both of them. I want to sort the second unordered
list based on the ordering of the first one.
ordered_list = ["first_name", "last_name", "language", "gender", "country", ]
unordered_list = ["country", "gender", "first_name", "last_name", "language",]
unordered_list.sort(key=ordered_list)
print(unordered_list)
PS: I have a looooonger list to work with, this is just an example.
GOAL: the unordered_list
items need to be sorted exactly how items are ordered in ordered_list
Is there a better approach than the one above that doesn't work?
Upvotes: 1
Views: 118
Reputation: 11342
Use the index as the key:
ordered_list = ["first_name", "last_name", "language", "gender", "country", ]
unordered_list = ["country", "gender", "first_name", "last_name", "language",]
unordered_list.sort(key= lambda x: ordered_list.index(x))
print(unordered_list)
Output
['first_name', 'last_name', 'language', 'gender', 'country']
Upvotes: 2