比如有一文件catfile.txt:1234567891011121314我想分成三列显示:catfile.txt1611271238134914510#!/usr/bin/envpythondefitercolumn(lines,column_line):block=[]forlninlines:bloc...
比如有一文件 cat file.txt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
我想分成三列显示: cat file.txt
1 6 11
2 7 12
3 8 13
4 9 14
5 10
#!/usr/bin/env python
def itercolumn(lines, column_line):
block = []
for ln in lines:
block.append(ln)
if len(block) == column_line:
yield block
block = []
if 0 < len(block) < column_line:
block = block + [''] * (column_line - len(block))
yield block
lns = [ln.strip() for ln in open("file.txt", 'r')]
column_num = 3
column_ln = (column_num + len(lns) - 1) / column_num
columns = [column for column in itercolumn(lns, column_ln)]
for row in zip(*columns):
print "\t".join(row)
求更简洁更高效的 PYTHON代码, 上面代码有点复杂
展开