[Tutor] Sorting a list of list
Peter Otten
__peter__ at web.de
Fri Jun 5 22:48:37 CEST 2015
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]]
itemgetter() accepts multiple indices:
>>> items = [
... ["one", "stephen", 20],
... ["two", "stephen", 10],
... ["three", "jim", 20]]
>>> from operator import itemgetter
>>> sorted(items, key=itemgetter(1, 2))
[['three', 'jim', 20], ['two', 'stephen', 10], ['one', 'stephen', 20]]
>>> sorted(items, key=itemgetter(2, 1))
[['two', 'stephen', 10], ['three', 'jim', 20], ['one', 'stephen', 20]]
For complex sort orders you can build on the fact that Python's sort is
"stable", i. e. equal items do not change their relative position. Just sort
by the "least significan key" first:
>>> items.sort(key=itemgetter(2), reverse=True)
>>> items.sort(key=itemgetter(1))
>>> items
[['three', 'jim', 20], ['one', 'stephen', 20], ['two', 'stephen', 10]]
More information about the Tutor
mailing list