itertools.groupby

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Apr 20 20:13:27 EDT 2013


On Sat, 20 Apr 2013 11:09:42 -0600, Jason Friedman wrote:

> I have a file such as:
> 
> $ cat my_data
> Starting a new group
> a
> b
> c
> Starting a new group
> 1
> 2
> 3
> 4
> Starting a new group
> X
> Y
> Z
> Starting a new group
> 
> I am wanting a list of lists:
> ['a', 'b', 'c']
> ['1', '2', '3', '4']
> ['X', 'Y', 'Z']
> []
> 
> I wrote this:
[...]
> I get the output I desire, but I'm wondering if there is a solution
> without the global counter.


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




-- 
Steven



More information about the Python-list mailing list