如果您在内存中有一个列表(来自读取文件),只需将列表重新格式化为您想要的:
input='''\
2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990'''
cols=2
data=input.split() # proxy for a file
print data
print '==='
for li in [data[i:i+cols] for i in range(0,len(data),cols)]:
print li
印刷:
['2.131583', '2.058964', '6.866568', '0.996470', '6.424396', '0.996004', '6.421990']
===
['2.131583', '2.058964']
['6.866568', '0.996470']
['6.424396', '0.996004']
['6.421990']
或者,使用一次 N 次文件读取习惯用法:
import itertools
cols=2
with open('/tmp/nums.txt') as fin:
for li in itertools.izip_longest(*[fin]*cols):
print li
# prints
('2.131583\n', '2.058964\n')
('6.866568\n', '0.996470\n')
('6.424396\n', '0.996004\n')
('6.421990', None)
如果您想要一种文件过滤器,您可以将其组合成一个迭代器,一个迭代器输出:
import itertools
cols=2
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
for li in itertools.izip_longest(*[fin]*cols):
fout.write('\t'.join(e.strip() for e in li if e)+'\n')
输出文件现在将是:
2.131583 2.058964
6.866568 0.996470
6.424396 0.996004
6.421990
如果您只想编写完整的数字集的输出,即文件末尾小于cols
总长度的剩余数字:
import itertools
cols=2
# last number '6.421990' not included since izip is used instead of izip_longest
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
for li in itertools.izip(*[fin]*cols):
fout.write('\t'.join(e.strip() for e in li)+'\n')
那么输出文件是:
2.131583 2.058964
6.866568 0.996470
6.424396 0.996004