2011-11-04 21 views
0

下面如何讓線由塊

自下而上「的數據」是由一列數字使代碼很簡單的問題,讓我們說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 

等等......因爲我需要處理所有的塊。

感謝您閱讀

回答

0

你的問題不是很清楚,但我想你可能想是這樣的:

with open ('test', 'r') as f: 
    data = f.readlines() 

blocksize = 4 
blocks = [data[i:i+blocksize] for i in xrange(len(data)/blocksize)] 

for block in blocks: 
    print ''.join(block) 

編輯:

with open ('test', 'r') as f: 
    data = f.readlines() 

blocksize = 4 

def block_generator(): 
    i = 0 
    while i < len(data): 
    yield data[i:i + blocksize] 
    i += blocksize 
    raise StopIteration 

for block in block_generator(): 
    print block 
+0

看起來是工作,我的意思是它不回答我的問題!我會盡力將其粘貼到我的代碼中。感謝堆! – eikonal

+0

是否有可能「返回」給出一個塊而不是三個,因爲我想和「打印」一樣? – eikonal

+0

哪個'return',我沒有?你的意思是像生成器一樣「產出」,這就是你在原始問題中似乎試圖實現的東西。我將用這樣的示例用法編輯我的解決方案。 – wim

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

非常感謝Token!我的數據實際上比我在這裏發佈的要複雜得多,但你給了我一個非常好的輸入。我會嘗試修改它並將其粘貼到我的代碼中!乾杯 – eikonal