[Tutor] Sort pointers -

Kent Johnson kent37 at tds.net
Wed Nov 24 21:11:28 CET 2004


Liam Clarke wrote:
> Hi all,
> 
> Thanks Kent. Question - is Python 2.4 release 1 considered a stable release?

Stable in the sense of feature-complete, yes. Stable in the sense of 
bug-free...not necessarily. It is a release candidate, not a final 
release. If you are just learning Python and writing simple scripts I 
would go for it. If you have a critical production application you are 
running, you probably want to wait for the final release.

>>Kent Johnson said unto the world upon 2004-11-24 06:05:
>>>In Python 2.3 you have two choices:
>>>- Use the decorate - sort - undecorate idiom (aka Schwartzian Transform)

OK, here is the explanation for decorate - sort - undecorate aka DSU aka 
Schwarzian transform. This idiom is generally considered better than 
writing a custom cmp function because it is faster in many cases.

The idea is to transform the list to be sorted into a list of tuples, 
where the first element of the tuple is the sort key and the second 
element is the original list element. This is the 'decorate' step. It is 
usually done with a list comprehension:

 >>> mp= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton 
also' : '006' , 'Captain Planet' : '000' }
 >>> it = mp.items()
 >>> it
[('Enid Blyton also', '006'), ('Captain Planet', '000'), ('James Bond', 
'007'), ('Enid Blyton', '005')]

 >>> dit = [ (item[1], item) for item in it ]
 >>> dit
[('006', ('Enid Blyton also', '006')), ('000', ('Captain Planet', 
'000')), ('007', ('James Bond', '007')), ('005', ('Enid Blyton', '005'))]

Sorting the decorated list produces the desired order, since the key is 
the first item in the tuple elements:

 >>> dit.sort()
 >>> dit
[('000', ('Captain Planet', '000')), ('005', ('Enid Blyton', '005')), 
('006', ('Enid Blyton also', '006')), ('007', ('James Bond', '007'))]
 >>>

A second list comprehension retrieves the original list elements from 
the decorated list. This is the 'undecorate' step:

 >>> it = [ item[1] for item in dit ]
 >>> it
[('Captain Planet', '000'), ('Enid Blyton', '005'), ('Enid Blyton also', 
'006'), ('James Bond', '007')]


A link about DSU in the Python FAQ:
http://www.python.org/doc/faq/programming.html#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python

Kent


More information about the Tutor mailing list