Sorting list of objets in Python/Django

694 views
Skip to first unread message

Nianbig

unread,
Sep 21, 2008, 1:43:07 PM9/21/08
to Django users
Hi,

I have a people-list like this:
>>> class a:
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> b = []
>>> b.append( a('Smith', 1) )
>>> b.append( a('Dave', 456) )
>>> b.append( a('Guran', 9432) )
>>> b.append( a('Asdf', 12) )

How do I sort this on their names e.g. ascending? I have tried
b.sort() and so on in all sorts of ways but I can´t figure this one
out..

Would be thankful for help.

/Nianbig

Fredrik Lundh

unread,
Sep 21, 2008, 1:45:24 PM9/21/08
to django...@googlegroups.com
Nianbig wrote:

this might get you going:

def mysortkey(x):
return x.name

b.sort(key=mysortkey)

</F>

Nianbig

unread,
Sep 21, 2008, 4:54:30 PM9/21/08
to Django users
Ah, thanks!

/Nianbig

Rodolfo

unread,
Sep 21, 2008, 5:38:25 PM9/21/08
to Django users
You could also achieve that using the __cmp__ magic method[1]:

<code>

class a:
def __init__(self, name, number):
self.name = name
self.number = number

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

def __repr__(self):
return "a(%s, %s)" % (repr(self.name), self.number)

b = []
b.append( a('Smith', 1) )
b.append( a('Dave', 456) )
b.append( a('Guran', 9432) )
b.append( a('Asdf', 12) )

b.sort()

print b

# [a('Asdf', 12), a('Dave', 456), a('Guran', 9432), a('Smith', 1)]

</code>


The __cmp__ method does the magic, it's used when you call b.sort().
I added __repr__ just to see legible output...


[1] http://docs.python.org/ref/customization.html

[]'s

Rodolfo

Steve Holden

unread,
Sep 21, 2008, 9:50:09 PM9/21/08
to django...@googlegroups.com
You could, but a key function is generally better, and the larger the
list the better (in the general case) it is likely to be. The problem is
that using __cmp__ requires the sort algorithm to make Python callbacks
from a C function for each object-pair comparison. Using the key
function, that function is called once to decorate each object in the
list, and the C sort function compares the decorated list items without
the need to call out to Python functions at all.

As with all general solutions, specific circumstances can alter this
general conclusion.

regards
Steve
Reply all
Reply to author
Forward
0 new messages