itertools.groupby
Jason Friedman
jsf80238 at gmail.com
Sat Apr 20 13:09:42 EDT 2013
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:
------------------------------------
#!/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:])
------------------------------------
I get the output I desire, but I'm wondering if there is a solution without
the global counter.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130420/c905d5f0/attachment.html>
More information about the Python-list
mailing list