Sunday, January 11, 2009

Sorting by class attributes

When you need to sort a sequence (e. g. a list) of objects you probably want to sort them by one of their attributes. How to to that?

Let's have this simple class:


class Record:
    def __init__(self):
        self.name = "noname"


now we have three objects of this class:


>>> r = Record()
>>> s = Record()
>>> t = Record()


And we give them some names


>>> r.name = "qwer"
>>> s.name = "asdf"
>>> t.name = "yxcv"


We have them in a list

>>> someList = [r, s, t]

And we want them to be sorted by their attribute name. This can be done by specifying the key argument of the sequence method .sort():


>>> someList.sort(key = lambda x: x.name)


That's all. The objects in the list are sorted by their name attributes.

P.S.:
The lambda x: x.name is a minimal function. For every x it returns x.name

No comments: