Sorting lists of lists by columns

Alex Martelli aleax at aleax.it
Tue Mar 4 11:39:44 EST 2003


Stephen Boulet wrote:

> Is there any list method available to sort lists of lists by columns? I'm
> thinking of a spreadsheet-type function where you might sort rows by the
> column x, y, and then z.

The Decorate-Sort-Undecorate idiom, which ends up playing the main role in
the Sorting and Searching chapter of the Python Cookbook, is perfect for
this task.  E.g.:

def sortByColumns(list2d, column_indices, in_place=False):
    aux = [ [ sl[i] for i in column_indices ] + [sl] for sl in list2d ]
    aux.sort()
    aux = [ sl[-1] for sl in aux ]
    if in_place: list2d[:] = aux
    else: return aux

This is MUCH faster, as well as simpler, than passing a comparison
function to the sort method.


Alex





More information about the Python-list mailing list