Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort in decreasing value first then increasing in second value [duplicate]

Tags:

python

sorting

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?

like image 591
Alexa Elis Avatar asked May 14 '13 07:05

Alexa Elis


2 Answers

This does it:

print sorted(student_tuples, key=lambda t: (-t[2], t[0]))
# [('john', 'A', 15), ('dave', 'C', 12), ('peter', 'B', 12)]
like image 99
RichieHindle Avatar answered Oct 26 '22 19:10

RichieHindle


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)]
like image 41
Adrian Ratnapala Avatar answered Oct 26 '22 19:10

Adrian Ratnapala