list organization question

Arnaud Delobelle arnodel at googlemail.com
Thu Dec 11 18:31:03 EST 2008


Robocop <bthayre at physics.ucsd.edu> writes:

> I have a list of objects, each object having two relevant attributes:
> date and id.  I'd like not only organize by id, but also by date.
> I.e. i would like to parse my list into smaller lists such that each
> new mini-list has a unique date, but consists of only objects with a
> specific id.  Are there any handy imports i could use to accomplish
> something like this?  I'm relatively new to python and as such don't
> know all of the preloaded functions at my disposal.  Thanks for any
> help in advance, the community here is always ridiculously helpful.

Look at itertools.groupby.

E.g.

from itertools import groupby

data = [ my objects ]

def getdate(x): return x.date

by_date = {}
for date, objs in groupby(sorted(data, key=getdate), getdate):
    by_date[date] = list(objs)
    # list(objs) is the list of all objects in data whose date is date

I'm sorry if this is a bit terse...

-- 
Arnaud



More information about the Python-list mailing list