Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters?
list, python, python-3.x, sorting
Solution
Pretty straight forward:
your_list.sort(key=lambda e: (-e[1], e[0]))
for example
>>> your_list = [('IL', 36), ('NJ', 81), ('CA', 81), ('DC', 52), ('TX', 39)]
>>> your_list.sort(key=lambda e: (-e[1], e[0]))
>>> your_list
[('CA', 81), ('NJ', 81), ('DC', 52), ('TX', 39), ('IL', 36)]
Note that the above sorts the list in place. If you want to wrap this in a function and not modify the original list, use `sorted`
def your_sort(your_list):
return sorted(your_list, key=lambda e: (-e[1], e[0]))
Problem
If my list is `[('IL', 36), ('NJ', 81), ('CA', 81), ('DC', 52), ('TX', 39)]`, how can I sort it so that my result will be `[('CA', 81), ('NJ', 81), ('DC', 52), ('TX', 39), ('IL', 36)]`?