Reputation: 171
Pretty easy question below
From the code below 'data' is made by a column of numbers, let's say 12 numbers (see below)
def block_generator():
with open ('test', 'r') as lines:
data = lines.readlines ()[5::]
for line in data:
if not line.startswith (" "): # this actually gives me the column of 12 numbers
block = # how to get blocks of 4 lines???
yield block
print line
56.71739
56.67950
56.65762
56.63320
56.61648
56.60323
56.63215
56.74365
56.98378
57.34681
57.78903
58.27959
How can I create blocks of of four numbers? For example
56.71739
56.67950
56.65762
56.63320
56.61648
56.60323
56.63215
56.74365
and so on... because I need to process all the blocks.
Thanks for reading
Upvotes: 0
Views: 187
Reputation: 156238
the itertools
module provides a recipe that does just what you need:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
Which looks like:
>>> corpus = (56.71739, 56.67950, 56.65762, 56.63320, 56.61648,
... 56.60323, 56.63215, 56.74365, 56.98378, 57.34681,
... 57.78903, 58.27959,)
>>> list(grouper(4, corpus))
[(56.71739, 56.6795, 56.65762, 56.6332),
(56.61648, 56.60323, 56.63215, 56.74365),
(56.98378, 57.34681, 57.78903, 58.27959)]
>>> print '\n\n'.join('\n'.join(group)
... for group
... in grouper(4, map(str, corpus)))
56.71739
56.6795
56.65762
56.6332
56.61648
56.60323
56.63215
56.74365
56.98378
57.34681
57.78903
58.27959
>>>
Upvotes: 2