Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

Tim Golden mail at timgolden.me.uk
Fri Sep 7 16:15:46 CEST 2007


cjt22 at bath.ac.uk wrote:
> Hi there
> 
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> 
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.

You're going to get a *lot* of answers on this one!

To start the ball rolling...

<code>
import random

class Step:

   def __init__ (self, name, startTime):
     self.name = name
     self.startTime = startTime

   def __cmp__ (self, other):
     return cmp (self.startTime, other.startTime)

   def __str__ (self):
     return str (self.startTime)
   __repr__ = __str__

steps = [Step (h, "%02d:00:00" % h) for h in range (10)]
random.shuffle (steps)
print "Shuffled:", steps

steps.sort ()
print "Sorted:", steps
</code>

In this case, I've given the class a ordering-semantic based
on its startTime attribute. Obviously, this only makes sense
if you *always* want your class to sort this way, rather than
in this one instance.

To do it on a per-sort basis, you *could* create simple per-sort
equivalent:

<code fragment>

def compare_by_startTime (one, other):
   return cmp (one.startTime, other.startTime)

steps.sort (cmp=compare_by_startTime)

</code>

or, in the case you're asking about, you could use the
operator module's attrgetter function to do what you want:

<code fragment>
import operator

steps.sort (key=operator.attrgetter ("startTime"))

</code>

TJG



More information about the Python-list mailing list