Preferred method of sorting/comparing custom objects
ian.g.kelly at gmail.com
Thu Feb 24 18:43:30 CET 2011
On Thu, Feb 24, 2011 at 9:41 AM, Jeremy <jlconlin at gmail.com> wrote:
> I recently found the wiki page on sorting (http://wiki.python.org/moin/HowTo/Sorting/). This page describes the new key parameter to the sort and sorted functions.
> What about custom objects? Can I just write __lt__, __gt__, etc. functions and not have to worry about the key parameter? Is that the preferred (i.e., fastest) way to do things or should I use a lambda function similar to what is given as an example on the wiki page?
> For my custom objects, I would prefer to write the comparison functions as that seems easiest in my situation, but I would like to know what is the preferred/accepted way.
If your objects naturally present a partial ordering, then you should
implement it. If they do not, or if your implementations of the rich
comparison functions would seem arbitrary in other contexts, then you
should not add them to the classes, and you should use a key function
More information about the Python-list