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

Tim Golden mail at
Fri Sep 7 16:15:46 CEST 2007

cjt22 at 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...

import random

class Step:

   def __init__ (self, name, startTime): = 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

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

<code fragment>

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

steps.sort (cmp=compare_by_startTime)


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"))



More information about the Python-list mailing list