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]]


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to