HELP:sorting list of outline numbers

Delaney, Timothy (Tim) tdelaney at avaya.com
Tue Aug 2 22:56:20 EDT 2005


Scott David Daniels wrote:

> For 2.3: (using DSU -- Decorate, Sort, Undecorate)
>      def numparts(outlinetext):
>          return [int(number) for number in outlinetext.split('.')]
> 
>      lst = ['1', '1.2', '1.12', '1.1', '3.1']
>      decorated = [(numparts(txt), txt) for txt in lst]
>      decorated.sort()
>      lst[:] = [txt for code, txt in decorated]

Slightly better to do::

     def numparts(outlinetext):
         return [int(number) for number in outlinetext.split('.')]

     lst = ['1', '1.2', '1.12', '1.1', '3.1']
     decorated = [(numparts(txt), i, txt) for i, txt in enumerate(lst)]
     decorated.sort()
     lst[:] = [txt[-1] for d in decorated]

This emulates the 2.4 sorting using `key` i.e. only the key is
evaluated, not the original object. It also ensures a stable sort, but
`sort` is stable in 2.3 anyway (not the case in earlier versions ...).

Tim Delaney



More information about the Python-list mailing list