HELP:sorting list of outline numbers

Robert Kern rkern at ucsd.edu
Tue Aug 2 21:37:58 EDT 2005


Felix Collins wrote:
> Hi All,
> does anyone know any cleaver tricks to sort a list of outline numbers.
> 
> An outline number is a number of the form...    1.2.3
> 
> they should be sorted in the following way...
> 
> 1
> 1.1
> 1.2
> 1.12
> 
> python's alpha sort (by design) sorts them...
> 
> 1
> 1.1
> 1.12
> 1.2
> 
> That's no good for me.
> I'm planning on splitting the strings into multiple lists of ints and 
> doing numerical sorts.
> 
> Thanks for any clever ideas that might make it easier.

Use the "key" keyword argument to list.sort().

In [1]: outline = ['1.12', '1.1', '1', '1.2']

In [2]: outline.sort(key=lambda x: map(int, x.split('.')))

In [3]: outline
Out[3]: ['1', '1.1', '1.2', '1.12']

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list