On 21 April 2013 01:13, Steven D'Aprano < steve+comp.lang.pyt...@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
-- http://mail.python.org/mailman/listinfo/python-list