itertools.groupby

Joshua Landau joshua.landau.ws at gmail.com
Sun Apr 21 23:09:04 EDT 2013


On 21 April 2013 01:13, Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:

> I wouldn't use groupby. It's a hammer, not every grouping job is a nail.
>
> Instead, use a simple accumulator:
>
>
> def group(lines):
>     accum = []
>     for line in lines:
>         line = line.strip()
>         if line == 'Starting a new group':
>             if accum:  # Don't bother if there are no accumulated lines.
>                 yield accum
>                 accum = []
>         else:
>             accum.append(line)
>     # Don't forget the last group of lines.
>     if accum: yield accum
>

Whilst yours is the simplest bar Dennis Lee Bieber's and nicer in that it
yields, neither of yours work for empty groups properly.

I recommend the simple change:

def group(lines):
    accum = None
    for line in lines:
        line = line.strip()
        if line == 'Starting a new group':
            if accum is not None:  # Don't bother if there are no
accumulated lines.
                yield accum
            accum = []
        else:
            accum.append(line)
    # Don't forget the last group of lines.
    yield accum

But will recommend my own small twist (because I think it is clever):

def group(lines):
lines = (line.strip() for line in lines)

if next(lines) != "Starting a new group":
 raise ValueError("First line must be 'Starting a new group'")

while True:
 acum = []

for line in lines:
if line == "Starting a new group":
 break

acum.append(line)

else:
 yield acum
break

yield acum
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130422/b70edd07/attachment.html>


More information about the Python-list mailing list