Demonstration
>>> mylist1 = ['alpha', 'green'] >>> mylist2 = ['blue', 'alpha', 'red'] >>> sort_order = ['red', 'blue', 'green', 'alpha'] >>> mylist1.sort(key=sort_order.index) >>> mylist1 ['green', 'alpha'] >>> mylist2.sort(key=sort_order.index) >>> mylist2 ['red', 'blue', 'alpha']
Explanation
The key parameter in list.sort causes the list to determine the order by comparing key(element) instead of element . For example, to make case-insensitive sorting, you can pass a key function that makes a string lowercase. Lower case elements are compared, but the original elements are preserved:
>>> x = ["age", "Bonkers", "cheese"] >>> x.sort() >>> x ['Bonkers', 'age', 'cheese'] >>> str.lower("Bonkers") 'bonkers' >>> x.sort(key=str.lower) >>> x ['age', 'Bonkers', 'cheese']
Using sort_order.index for the key uses the index that the element has in the sort_order list to determine the order instead of the element itself. So, 'red' uses 0 , 'blue' uses 1 , etc ... the result is that the sorted list is sorted according to where each item is in sort_order .
source share