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


Groups > comp.lang.python > #43973 > unrolled thread

Re: itertools.groupby

Started byDennis Lee Bieber <wlfraed@ix.netcom.com>
First post2013-04-20 19:39 -0400
Last post2013-04-20 19:39 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: itertools.groupby Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-04-20 19:39 -0400

#43973 — Re: itertools.groupby

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2013-04-20 19:39 -0400
SubjectRe: itertools.groupby
Message-ID<mailman.865.1366501207.3114.python-list@python.org>
On Sat, 20 Apr 2013 11:09:42 -0600, Jason Friedman <jsf80238@gmail.com>
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
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web