Answers for "custom sort list python"

0

python sort a list by a custom order

# Example usage:
list_to_sort = [('U', 23), ('R', 42), ('L', 17, 'D')]
custom_sort_order = ['R', 'D', 'L', 'U']
sorted(list_to_sort, key=lambda list_to_sort: custom_sort_order.index(list_to_sort[0]))
# Where 0 is the tuple index to use for sorting by custom order
--> [('R', 42), ('L', 17, 'D'), ('U', 23)]
Posted by: Guest on October-04-2020

Python Answers by Framework

Browse Popular Code Answers by Language