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


Groups > comp.lang.python > #44075

Re: itertools.groupby

From Neil Cerutti <neilc@norwich.edu>
Newsgroups comp.lang.python
Subject Re: itertools.groupby
Date 2013-04-22 14:24 +0000
Organization Norwich University
Message-ID <atkvgbFto6uU1@mid.individual.net> (permalink)
References <mailman.855.1366477790.3114.python-list@python.org>

Show all headers | View raw


On 2013-04-20, Jason Friedman <jsf80238@gmail.com> 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']
> []

Hrmmm, hoomm. Nobody cares for slicing any more.

def headered_groups(lst, header):
    b = lst.index(header) + 1
    while True:
        try:
            e = lst.index(header, b)
        except ValueError:
            yield lst[b:]
            break
        yield lst[b:e]
        b = e+1

for group in headered_groups([line.strip() for line in open('data.txt')],
        "Starting a new group"):
    print(group)

-- 
Neil Cerutti

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