itertools.groupby

Steve Howell showell30 at yahoo.com
Tue May 29 23:53:00 EDT 2007


On May 29, 2:34 am, Raymond Hettinger
<pyt... at rcn.com> wrote:
> The gauntlet has been thrown down.  Any creative
> thinkers
> up to the challenge?  Give me cool recipes.
> 

I don't make any claims to coolness, but I can say
that I myself would have written the code below with
significantly more complexity before groupby(), and I
can see the utility for this code in dealing with
certain mail programs.

The code is phrased verbosely, even if you remove the
tests, but the meat of it could be boiled down to a
one-liner.


import itertools
lines = '''
This is the
first paragraph.

This is the second.
'''.splitlines()
# Use itertools.groupby and bool to return groups of
# consecutive lines that either have content or don't.
for has_chars, frags in itertools.groupby(lines,
bool):
    if has_chars:
        print ' '.join(frags)
# PRINTS:
# This is the first paragraph.
# This is the second.



       
____________________________________________________________________________________Need a vacation? Get great deals
to amazing places on Yahoo! Travel.
http://travel.yahoo.com/



More information about the Python-list mailing list