Sorting a list of classes

Quinn Dunkan quinn at ngwee.ugcs.caltech.edu
Mon Apr 24 06:26:16 CEST 2000


On Mon, 24 Apr 2000 00:08:49 -0400, lexberezhny <lexberezhny at email.msn.com>
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?

See the docs for sort():

addr_book.sort(lambda a, b: cmp(a.name, b.name))

Alternately, since you wanted the logic in the class (see the lang ref under
"special method names"):

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



More information about the Python-list mailing list