[Tutor] Help with iterators

Mitya Sirenef msirenef at lightbird.net
Fri Mar 22 03:31:53 CET 2013


On 03/21/2013 10:20 PM, Steven D'Aprano wrote:
> 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.


OP said his code produces the needed result and I think his description
probably doesn't match what he really intends to do (he also said he
wants the same code rewritten using groupby). I reproduced the logic of
his code... hopefully he can step in and clarify!



>
 > 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
 >
 >
 >
 >


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

A little bad taste is like a nice dash of paprika.
Dorothy Parker



More information about the Tutor mailing list