Entry
How do I sort a list based on some attribute(s) of the objects in the list?
How do I sort a list based on some attribute(s) of the objects in the list?
Nov 3rd, 2008 00:30
Daniel Gonzalez Gasull, games games, Michael Chermside, Emile van Sebille, Max M
Suppose you have a list of objects with certain attributes:
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self,x,y):
... self.x = x
... self.y = y
... def __repr__(self):
... return 'Foo(%r,%r)' % (self.x, self.y)
...
>>> aList = [Foo(3,4), Foo(4,5), Foo(3,7), Foo(4,2), Foo(1,0)]
And suppose you want to sort the foo's by their x value, and sub-sort
by
the y value. It's a very simple one-liner:
>>> aList.sort( lambda a,b: cmp( (a.x,a.y), (b.x,b.y) ) )
>>> aList
[Foo(1,0), Foo(3,4), Foo(3,7), Foo(4,2), Foo(4,5)]
Notice that if you didn't need to sub-sort on a second attribute, it
would be even simpler... the lambda would be simply: "lambda a,b:
cmp(a.x,b.x)".