Reputation: 877
I have a list with benchmark order of items:
benchmark = ['Wind', 'Sun', 'Tree', 'Human', 'Cat']
Also I have many small lists with two items:
list1 = ['Cat', 'Wind']
list2 = ['Tree', 'Sun']
list3 = ['Wind', 'Human']
I want to sort them using order in benchmark. So expected output is:
list1 = ['Wind', 'Cat']
list2 = ['Sun', 'Tree']
list3 = ['Wind', 'Human']
How can I do it in most efficient way?
Upvotes: 0
Views: 76
Reputation: 878
Try this,
benchmark = ['Wind', 'Sun', 'Tree', 'Human', 'Cat']
list1 = ['Cat', 'Wind']
list2 = ['Tree', 'Sun']
list3 = ['Wind', 'Human']
print(sorted(list1, key=benchmark.index))
print(sorted(list2, key=benchmark.index))
print(sorted(list3, key=benchmark.index))
Upvotes: 2
Reputation: 323
you can use zip
function
sorted_list1 = [item for _,item in sorted(zip(benchmark,list1))]
Upvotes: 3