Let say I have :
student_tuples = [ ('john', 'A', 15),
('peter', 'B', 12),
('dave', 'C', 12)]
How do I sort it to be like this:
student_tuples = [('john', 'A', 15), ('dave', 'C', 12), ('peter', 'B', 12)]
What I can think is:
from operator import itemgetter
sorted(student_tuples, key=itemgetter(2,0), reverse=True)
but then the output will be:
student_tuples = [('john', 'A', 15), ('peter', 'B', 12), ('dave', 'C', 12)]
and that is not what I want. How can I do it using itemgetter or any other easier way?
This does it:
print sorted(student_tuples, key=lambda t: (-t[2], t[0]))
# [('john', 'A', 15), ('dave', 'C', 12), ('peter', 'B', 12)]
Write your own key-getting function.
student_tuples = [ ('john', 'A', 15), ('peter', 'B', 12), ('dave', 'C', 12)]
def student_key(args):
name, letter, number = args
return (-number, name)
>>> sorted(student_tuples, key=student_key)
[('john', 'A', 15), ('dave', 'C', 12), ('peter', 'B', 12)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With