Home > front end >  How to sort a Tuple using two parameters?
How to sort a Tuple using two parameters?

Time:11-12

The Tuple contains [('John',32),('Jane',22),('Doe',32),('Mario',55)]. I want to sort the tuple by its 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)].

CodePudding user response:

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 them to be:

>>> from operator import itemgetter
>>> sorted(lot, key=itemgetter(1,0))
[('Jane', 22), ('Doe', 32), ('John', 32), ('Mario', 55)]
  • Related