Trouble sorting a list of objects by attributes
Miki
miki.tebeka at gmail.com
Fri Feb 6 15:56:25 EST 2009
> I've found myself stumped when trying to organize this list of
> objects. The objects in question are timesheets which i'd like to
> sort by four attributes:
>
> class TimeSheet:
> department = string
> engagement = string
> date = datetime.date
> stare_hour = datetime.time
>
> My ultimate goal is to have a list of this timesheet objects which are
> first sorted by departments, then within each department block of the
> list, have it organized by projects. Within each project block i
> finally want them sorted chronologically by date and time.
Python "natural" sort for tuples is doing the right thing for you, for
example:
from operator import attrgetter
from random import randint
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "(%s, %s)" % (self.x, self.y)
points = [Point(randint(1, 10), randint(1, 10)) for i in range(10)]
print points
points.sort(key=attrgetter("x", "y"))
print points
Gave me:
[(2, 3), (1, 4), (4, 4), (6, 6), (2, 10), (3, 5), (7, 1), (3, 6), (4,
1), (9, 6)]
[(1, 4), (2, 3), (2, 10), (3, 5), (3, 6), (4, 1), (4, 4), (6, 6), (7,
1), (9, 6)]
Points first sorted by 'x' and then by 'y'.
HTH,
--
Miki <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com
More information about the Python-list
mailing list