Will S Will S - 1 year ago 91
Python Question

How do I sort the same index of a tuple by Numerically (descending) and Alphabetically? [Python]

I have been set a task to sort a given list of tuples through a parameter of a function like this. I have to get the function to operate with only two lines of code.
The sort order is as such:
1) Grade
2) Surname
3) Forename

So for example one doctest would be:

sortStudents([('Tim Smith', 54), ('Anna Smith', 88), ('Barry Thomas', 88)])

This is what I have so far:

def sortStudents(a):
return (sorted(a, key=lambda x: (-x[1], x[0].split()[1], x[0].split()[0])))

And I have got these tests to work. However the last doctest I can't get to pass is one with Alphabetical grades rather than numerical ones. And as I am sorting in descending numerical values (by index) it would reverse the alphabetical sort at the same time. An example of the doctest would be:

sortStudents([('Tim Jones', 'C'), ('Anna Smith', 'B'), ('Barry Thomas', 'A')])

Thanks in advance.

Answer Source

You need to check the grade type (string or integer) to determine how the sorting should be done:

def sortStudents(a):
    return sorted(a, key=lambda x: [-x[1] if isinstance(x[1], int) else x[1]] 
                                   + x[0].split()[::-1])

You may also the name split once, and reverse the list, instead of splitting twice.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download