我有一个标签列表,数据如下。在
['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']
我需要把它们打印到控制台上。为此,我遍历列表,并用制表符('\t')打印出每个元素。在
但是,不幸的是,结果并不那么美好。在
^{pr2}$标签和数据的字符串长度是可变的,并且没有很好地对齐。在
Python有解决这个问题的方法吗?在
在迈克·德西莫内的回答下,我可以制作出一台漂亮的打印机,可以用于我的目的。valueResults是一个双精度列表。在
labels = queryResult.names
valueResults = queryResult.result
# get the maximum width
allData = valueResults
allData.insert(0,labels)
transpose = zip(*valueResults) # remove the sequence as a parameter
#print transpose
for value in transpose:
# value is integer/float/unicode/str, so make it length of str
newValue = [len(str(i)) for i in value]
columnWidth = max(newValue)
columnWidths.append(columnWidth)
dividers.append('-' * columnWidth)
dblDividers.append('=' * columnWidth)
label = value[0]
paddedLabels.append(label.center(columnWidth))
paddedString = ""
for values in valueResults[1:]:
paddedValue = []
for i, value in enumerate(values):
svalue = str(value)
columnWidth = columnWidths[i]
paddedValue.append(svalue.center(columnWidth))
paddedString += '| ' + ' | '.join(paddedValue) + ' |' + '\n'
string += '+-' + '-+-'.join(dividers) + '-+' + '\n'
string += '| ' + ' | '.join(paddedLabels) + ' |' + '\n'
string += '+=' + '=+='.join(dblDividers) + '=+' + '\n'
string += paddedString
string += '+-' + '-+-'.join(dividers) + '-+' + '\n'
这就是结果。在
+----+---------+-----------+------------+----------+-----------+--------------+ | id | Version | chip_name | xversion | device | opt_param | place_effort | +====+=========+===========+============+==========+===========+==============+ | 1 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | | 2 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | +----+---------+-----------+------------+----------+-----------+--------------+
谢谢你的帮助。在
在内容打印出来之前用ljust填充内容。在
输出:
^{pr2}$你可以试试这个
来自http://docs.python.org/tutorial/inputoutput.html
:
后面的整数是填充。在或者更好
^{pr2}$像这样:
输出:
^{pr2}$如果你想变得花哨,就让它reStructuredText-准备就绪:
输出:
相关问题 更多 >
编程相关推荐