HELP:sorting list of outline numbers

Scott David Daniels Scott.Daniels at Acm.Org
Wed Aug 3 16:31:33 CEST 2005

Delaney, Timothy (Tim) wrote:
> Scott David Daniels wrote:
>>For 2.3: (using DSU -- Decorate, Sort, Undecorate)
>>     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::
>      ...
>      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]

In the particular case given, I don't think it matters.

In general, however, I agree the latter is a better idea.  Just
so someone hopping in here is clear about what is better, and
explicitly _not_ because I think Tim misunderstands the issue,
The latter version, in the case of a match on the "decorated"
version compares first the "key", and then, if the keys match,
it compares the position in the list.  In no case does it actually
compare the original list elements.  The 2.4 version (just using the
key= form of sort) does the same kind of thing; it avoids comparing
the element and only compares keys.  The reason you care about this
is that is can be arbitrarily expensive to compare elements, or the
elements themselves may be "incomparable" (think of complex numbers).

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list