[Tutor] Sorting a list of list

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Jun 5 22:49:27 CEST 2015


On 05/06/2015 21:16, Stephen Nelson-Smith wrote:
> As part of my league secretary program (to which thread I shall reply again
> shortly), I need to sort a list of lists.  I've worked out that I can use
> sorted() and operator.itemgetter to sort by a value at a known position in
> each list.  Is it possible to do this at a secondary level?  So if the
> items are the same, we use the secondary key?
>
> Current function:
>
>>>> def sort_table(table, col=0):
> ...     return sorted(table, key=operator.itemgetter(col), reverse=True)
> ...
>>>> sort_table(results, 6)
> [['spip', 2, 2, 0, 10, 0, 4], ['hpip', 2, 0, 2, 2, 8, 0]]
>
> S.
>

Asked myself the very same thing earlier today so had the answer at my 
fingertips, taken from https://docs.python.org/3/howto/sorting.html

<quote>
The operator module functions allow multiple levels of sorting. For 
example, to sort by grade then by age:

 >>>
 >>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
</quote>

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list