Sorting lists of lists by columns

sismex01 at hebmex.com sismex01 at hebmex.com
Tue Mar 4 17:15:27 CET 2003


> From: Stephen Boulet [mailto:stephen.boulet at motorola.com]
> Sent: Tuesday, March 04, 2003 8:58 AM
> 
> 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.
> 
> -- Stephen
>

Hello.

How does your data look like?
Is it a list of tuples?

It's important for us to know that, because that can make
all the difference.

I'm going to assume that you have your data set up as a list
of tuples, where each tuple is a row.  The simplest approach
is to simply .sort() your list, since tuple-sorting is
quite fast.

If your tuple elements aren't arranged from most- to lease-
significant, then you'd need to reorder your tuple elements,
sort, and then reorder again.  This is known in Pythonspeak
as a "decorate-sort-undecorate" manouver :-)

def sort_tuplist(Data, *columns):
   """*columns contiains the numbers of the columns in
      significance order.
   """
   def Decorator(Row, *columns):
      if columns:
         return tuple([ Row[x] for x in columns ] + list(Row))
      return tuple(Row)
   def Undecorator(Row, *columns):
      if columns: return Row[-1]
      return Row
   Data = [ Decorator(row,columns) for row in Data ]
   Data.sort()
   Data = [ Undecorator(row,columns) for row in Data ]
   return Data

This procedure first "decorates" a list (using the list
comprehension and the Decorator function; sort the resulting
list, and then returns an "undecorated" version, which
is the original tuple.

HTH :-)

-gustavo

pd: I didn't test it, so it "should" work ;-)






More information about the Python-list mailing list