Trouble sorting a list of objects by attributes

R

rdmurray

Quoth Robocop said:
Hello again,
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.

To sort the strings i tried:

timesheets.sort(key=operator.attrgetter('string'))

which is not doing anything to my list unfortunately; it leaves it
untouched.

Python 2.6.1 (r261:67515, Jan 7 2009, 17:09:13)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information. ... def __init__(self, department): self.department=department
... def __repr__(self): return "Timesheet(%s)" % self.department
...
>>> timesheets = [Timesheet('abc'), Timesheet('def'), Timesheet('acd')]
>>> timesheets [Timesheet(abc), Timesheet(def), Timesheet(acd)]
>>> import operator
>>> timesheets.sort(key=operator.attrgetter('department'))
>>> timesheets
[Timesheet(abc), Timesheet(acd), Timesheet(def)]

The key bit here being the argument to attrgetter, which is the name
of the attribute to use as they key.

--RDM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top