0

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?

2 Answers 2

3

you can use zip function

sorted_list1 = [item for _,item in sorted(zip(benchmark,list1))]
1
  • Your code works whan I use English words. But order doesn't change with Russian words. Is it Cyrillic problem?
    – Igor K.
    Sep 26, 2020 at 10:33
2

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))
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.