Issue
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)]
.
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)]
Answered By - dawg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.