Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a list by number first in descending order and then by alphabet in ascending order

I have a list

ff = [('o', 2), ('l', 1), ('e', 1), ('g', 2)]

and i want to sort it in such a way in which it get sorted by number in descending order and if any element have same number then it get sorted by alphabet in ascending order, like this

ff = [('g', 2), ('o', 2), ('e', 1), ('l', 1)]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use sorted with parameter key:

ff = [('o', 2), ('l', 1), ('e', 1), ('g', 2)]

output = sorted(ff, key=lambda x: (-x[1], x[0]))

print(output) # [('g', 2), ('o', 2), ('e', 1), ('l', 1)]

When a tuple is given as key, sorted sorts the list lexicographically. In this case it first sorts according to the second element in descending order (-x[1]) and then sorts according to the first element in ascending order (x[0]).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading