Preferred method of sorting/comparing custom objects

J

Jeremy

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. functionsand 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.

Thanks,
Jeremy
 
C

Chris Rebert

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.

Thanks,
Jeremy

Please don't make duplicate posts to the mailinglist/newsgroup. If you
need to make corrections to a posting, do it as a follow-up to the
original post.

- Chris
 
I

Ian Kelly

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 andsorted 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
instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top