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): = "noname"

now we have three objects of this class:

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

And we give them some names

>>> = "qwer"
>>> = "asdf"
>>> = "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:

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

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

No comments: