对齐数字列(以表格格式打印输出)
我有一些数据(数字),它们是以以下格式保存的(举个例子):
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567
...
有没有什么方法可以用Python把这些数字对齐,并把它们变成这样:
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567
(我无法预测每列的大小)。
7 个回答
4
#!/usr/bin/env python
class ALIGN:
LEFT, RIGHT = '-', ''
class Column(list):
def __init__(self, name, data, align=ALIGN.RIGHT):
list.__init__(self, data)
self.name = name
width = max(len(str(x)) for x in data + [name])
self.format = ' %%%s%ds ' % (align, width)
class Table:
def __init__(self, *columns):
self.columns = columns
self.length = max(len(x) for x in columns)
def get_row(self, i=None):
for x in self.columns:
if i is None:
yield x.format % x.name
else:
yield x.format % x[i]
def get_rows(self):
yield ' '.join(self.get_row(None))
for i in range(0, self.length):
yield ' '.join(self.get_row(i))
def __str__(self):
return '\n'.join(self.get_rows())
针对你的例子:
if __name__ == '__main__':
print Table(
Column("", [234, 32, 23456]),
Column("", [127, 12, 2]),
Column("", [34, 4, 1]),
Column("", [23, 4, 444]),
Column("", [45567, 45, 567])
)
它将产生:
234 127 34 23 45567
32 12 4 4 45
23456 2 1 444 567
改编自 http://code.activestate.com/recipes/577202-render-tables-for-text-interface/
10
你需要找到列的大小,可能的方法是读取所有数据,然后找出最大的宽度。
>>> line='234 127 34 23 45567'
>>> line.split()
['234', '127', '34', '23', '45567']
>>> max(map(len, line.split()))
5
遍历所有行,来找出列的大小(比如说,5)。用百分号格式化
来构建格式化的行是很简单的。
>>> colsize = 5
>>> ' '.join(('%*s' % (colsize, i) for i in line.split()))
' 234 127 34 23 45567'
>>>
15
这里有一个简单的例子,展示了如何设置不同宽度的列:
data = '''\
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567'''
# Split input data by row and then on spaces
rows = [ line.strip().split(' ') for line in data.split('\n') ]
# Reorganize data by columns
cols = zip(*rows)
# Compute column widths by taking maximum length of values per column
col_widths = [ max(len(value) for value in col) for col in cols ]
# Create a suitable format string
format = ' '.join(['%%%ds' % width for width in col_widths ])
# Print each row using the computed format
for row in rows:
print format % tuple(row)
这个例子会输出:
234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567