itertools.groupby
Carsten Haese
carsten at uniqsys.com
Mon May 28 09:50:24 EDT 2007
On Sun, 2007-05-27 at 20:28 -0700, Paul Rubin wrote:
> fst = operator.itemgetter(0)
> snd = operator.itemgetter(1)
>
> def bates(fd):
> # generate tuples (n,d) of lines from file fd,
> # where n is the record number. Just iterate through all lines
> # of the file, stamping a number on each one as it goes by.
> n = 0 # record number
> for d in fd:
> if d.startswith('New Record'): n += 1
> yield (n, d)
>
> def records(fd):
> for i,d in groupby(bates(fd), fst):
> yield imap(snd, d)
Now there's a clever variation of the Schwartzian transform: decorate,
groupby, undecorate.
That's a nice example of groupby, but it could benefit from using better
variable names.
--
Carsten Haese
http://informixdb.sourceforge.net
More information about the Python-list
mailing list