Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44030

Re: itertools.groupby

References <mailman.855.1366477790.3114.python-list@python.org> <51732f27$0$29977$c3e8da3$5496439d@news.astraweb.com>
From Joshua Landau <joshua.landau.ws@gmail.com>
Date 2013-04-22 04:09 +0100
Subject Re: itertools.groupby
Newsgroups comp.lang.python
Message-ID <mailman.895.1366600191.3114.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On 21 April 2013 01:13, Steven D'Aprano <
steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

itertools.groupby Jason Friedman <jsf80238@gmail.com> - 2013-04-20 11:09 -0600
  Re: itertools.groupby Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-04-21 00:13 +0000
    Re: itertools.groupby Joshua Landau <joshua.landau.ws@gmail.com> - 2013-04-22 04:09 +0100
  Re: itertools.groupby Neil Cerutti <neilc@norwich.edu> - 2013-04-22 14:24 +0000
    Re: itertools.groupby Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-04-22 15:49 +0100
      Re: itertools.groupby Neil Cerutti <neilc@norwich.edu> - 2013-04-22 15:04 +0000
    Re: itertools.groupby Chris Angelico <rosuav@gmail.com> - 2013-04-23 01:14 +1000

csiph-web