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 Tuple using two parameters?

A list of tuples contains [('John',32),('Jane',22),('Doe',32),('Mario',55)]. I want to sort the list by age and the same aged people by their names in alphabetical order ? So far I have used only Lambda function inside a sorted() function with key being either name or age ?

The output should be -> [('Jane',22),('Doe',32),('John',32),('Mario',55)].

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 :

Given:

>>> lot=[('John',32),('Jane',22),('Doe',32),('Mario',55)]

You can form a new tuple:

>>> sorted(lot, key=lambda t: (t[1],t[0]))
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]

Or, in this case, you can reverse the tuple:

>>> sorted(lot, key=lambda t: t[::-1])
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]

You can also use itemgetter with two arguments in the order you want the resulting key tuple to be:

>>> from operator import itemgetter
>>> sorted(lot, key=itemgetter(1,0))
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]
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