[Tutor] Help with iterators

Steven D'Aprano steve at pearwood.info
Fri Mar 22 03:20:09 CET 2013


On 22/03/13 12:39, Mitya Sirenef wrote:

> You can do it with groupby like so:
>
>
> from itertools import groupby
> from operator import itemgetter
>
> maxDate = "2013-03-21"
> mmax    = list()
>
> obs.sort(key=itemgetter('date'))
>
> for k, group in groupby(obs, key=itemgetter('date')):
>      group = [dob for dob in group if dob['realtime_start'] <= maxDate]
>      if group:
>          group.sort(key=itemgetter('realtime_start'))
>          mmax.append(group[-1])
>
> pprint.pprint(mmax)


This suffers from the same problem of finding six records instead of one,
and that four of the six have start dates before the given date instead
of after it.

Here's another solution that finds all the records that start on or after
the given data (the poorly named "maxDate") and displays them sorted by
date.


selected = [rec for rec in obs if rec['realtime_start'] >= maxDate]
selected.sort(key=lambda rec: rec['date'])
print selected




-- 
Steven


More information about the Tutor mailing list