Sorting a list of classes

Andrew Dalke dalke at acm.org
Mon Apr 24 05:04:35 EDT 2000


lexberezhny wrote:
>If i have a python list of classes, can i do something like
classList.sort()
>and how can i control this behavior within the classes. ie
>i have a address book, and a have a class called 'Person', and it has an
>attribute Person.Name, so i have a list of 'Person's how can i sort the
>list, and maybe sort it by name? do i have to write my own function or can
i
>use list.sort() some how?


I wrote a mini-HOWTO on this subject.  It's at
http://python.org/doc/howto/sorting/sorting.html

If you will only ever sort on name, you can implement the __cmp__
method in your Person

class Person:
  ...
  def __cmp__(self, other):
    return cmp(self.Name, other.Name)

Most likely you will want to pass the comparison function to sort(),
as in

def byName(x, y):
   return cmp(x.Name, y.Name)

nameList.sort(byName)

There are more variations in that HOWTO.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list