擅长:python、mysql、java
<p>我也遇到了同样的问题。管理层希望从某种表格格式的数据中打印出一份漂亮的报告。在</p>
<p>我不想只做一堆带有“魔力”空格的print语句来修复对齐,所以我想出了一个python函数:</p>
<pre><code>def column(filename, data, indent=0):
"""This function takes a list of lists and produces columized output"""
# get the width of the columns
width = []
for mylist in data:
for count, d in enumerate(mylist):
if count > (len(width)-1):
width.append(len(str(d)))
elif len(str(d)) > width[count]:
width[count] = len(str(d))
# print the data
for mylist in data:
line = '{0:<{indent}}'.format('', indent=indent)
for count, d in enumerate(mylist):
try:
line = '%s%s' % (line, '{0:{w},} '.format(d, w=width[count]))
except ValueError, e:
line = '%s%s' % (line, '{0:{w}} '.format(d, w=width[count]))
filename.write(line)
filename.write('\n')
</code></pre>
<p>它不是完美的,你需要调整它来产生你想要的输出。最具体地说,它当前需要一个列表,因为我希望以特定的顺序传递,而字典没有被排序。在</p>