Re: itertools.groupby

Discussion in 'Python' started by Dennis Lee Bieber, Apr 21, 2013.

  1. On Sat, 20 Apr 2013 11:09:42 -0600, Jason Friedman <>
    declaimed the following in gmane.comp.python.general:


    > I am wanting a list of lists:
    > ['a', 'b', 'c']
    > ['1', '2', '3', '4']
    > ['X', 'Y', 'Z']
    > []
    >
    > I wrote this:
    > ------------------------------------
    > #!/usr/bin/python3
    > from itertools import groupby
    >
    > def get_lines_from_file(file_name):
    > with open(file_name) as reader:
    > for line in reader.readlines():
    > yield(line.strip())
    >
    > counter = 0
    > def key_func(x):
    > if x.startswith("Starting a new group"):
    > global counter
    > counter += 1
    > return counter
    >
    > for key, group in groupby(get_lines_from_file("my_data"), key_func):
    > print(list(group)[1:])


    Given that the input is already grouped, in sequential terms...

    I'd probably avoid the whole groupby overhead since the processing
    is basically equivalent to a "report break".

    Untested/pseudo-code (I suspect this logic won't give you the empty
    last group...)

    result = []
    group = None
    for line in fin:
    if line.startswith("Starting..."):
    if group:
    result.append(group)
    group = []
    else:
    group.append(line)

    Hmmm... last group handling?

    if result and group == []:
    result.append(group)
    # if result we had data, and if group == [] the last input was
    "start a new group", so append the empty list.

    > I get the output I desire, but I'm wondering if there is a solution without
    > the global counter.


    No counters, no esoteric function calls... Just a straight through
    read/collect sequence.
    --
    Wulfraed Dennis Lee Bieber AF6VN
    HTTP://wlfraed.home.netcom.com/
    Dennis Lee Bieber, Apr 21, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. G?nter Jantzen

    whatsnew 2.4 about itertools.groupby:

    G?nter Jantzen, Jun 9, 2004, in forum: Python
    Replies:
    0
    Views:
    276
    G?nter Jantzen
    Jun 9, 2004
  2. Replies:
    3
    Views:
    322
    Fredrik Lundh
    May 25, 2006
  3. 7stud

    itertools.groupby

    7stud, May 27, 2007, in forum: Python
    Replies:
    13
    Views:
    589
    =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=
    Jun 5, 2007
  4. Steve Howell

    Re: itertools.groupby

    Steve Howell, May 27, 2007, in forum: Python
    Replies:
    13
    Views:
    529
  5. Tobiah

    itertools.groupby

    Tobiah, Jan 15, 2008, in forum: Python
    Replies:
    2
    Views:
    295
    Tobiah
    Jan 16, 2008
Loading...

Share This Page