[Python Wpg] Sort a list of tuples!

Stuart Williams stuartw at mts.net
Sun Apr 23 22:27:01 EDT 2006


>>>>> Brent Durksen writes:
> Subject: [Python Wpg] Sort a list of tuples!

> Well, I went on to answer my own question.  I created a list of tuples, 
> in the format (points, name) and sorted the whole list...

This is known as the Decorate Sort Undecorate (DSU) idiom in Python.
See for example http://wiki.python.org/moin/HowTo/Sorting or
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234.

Python 2.4 added a key parameter to the built-in sort method which
internally uses DSU making this even easier.  Add itemgetter from the
operator module and you can do much of what you want with this:

  sorted(d.items(), key=operator.itemgetter(1), reverse=True)


Also Note that almost everywhere one sees "for i in range(len(foo)):"
one can replace it with "for item in foo:"

Stuart.



More information about the Winnipeg mailing list