list organization question

Robocop bthayre at physics.ucsd.edu
Thu Dec 11 18:38:14 EST 2008


On Dec 11, 3:31 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> Robocop <btha... 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

This looks to be exactly what i'm looking for!  I will try and
implement this immediately, thank you all for the suggestions.



More information about the Python-list mailing list