python sort a list by a custom order

Solutions on MaxInterview for python sort a list by a custom order by the best coders in the world

showing results for - "python sort a list by a custom order"
Julián
04 Jan 2017
1# Example usage:
2list_to_sort = [('U', 23), ('R', 42), ('L', 17, 'D')]
3custom_sort_order = ['R', 'D', 'L', 'U']
4sorted(list_to_sort, key=lambda list_to_sort: custom_sort_order.index(list_to_sort[0]))
5# Where 0 is the tuple index to use for sorting by custom order
6--> [('R', 42), ('L', 17, 'D'), ('U', 23)]