Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters? -


if list [('il', 36), ('nj', 81), ('ca', 81), ('dc', 52), ('tx', 39)],

how can sort result [('ca', 81), ('nj', 81), ('dc', 52), ('tx', 39), ('il', 36)]?

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 above sorts list in place. if want wrap in function , not modify original list, use sorted

def your_sort(your_list):     return sorted(your_list, key=lambda e: (-e[1], e[0])) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -