如何按块获取线条

时间:2011-11-04 00:20:09

标签: python iterator

下面非常简单的问题

从下面的代码中,“数据”由一列数字组成,假设有12个数字(见下文)

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

如何创建四个数字的块?例如

56.71739
56.67950
56.65762
56.63320

56.61648
56.60323
56.63215
56.74365

依此类推......因为我需要处理所有的块。

感谢您阅读

1 个答案:

答案 0 :(得分:2)

itertools模块提供了满足您需求的配方:

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)

看起来像:

>>> 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
>>>