漂亮的Python打印机?

2024-09-28 03:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个标签列表,数据如下。在

['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     |
+----+---------+-----------+------------+----------+-----------+--------------+

谢谢你的帮助。在


Tags: in列表forstringvaluespeedjointranspose
3条回答

在内容打印出来之前用ljust填充内容。在

import sys

def maxwidth(table, index):
    """Get the maximum width of the given column index"""
    return max([len(str(row[index])) for row in table])

def pprint_table(table):
    colpad = []

    for i in range(len(table[0])):
        colpad.append(maxwidth(table, i))

    for row in table:
        print str(row[0]).ljust(colpad[0] + 1),
        for i in range(1, len(row)):
            col = str(row[i]).rjust(colpad[i] + 2)
            print "", col,
        print ""

a = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort']
b = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']

# Put it in the table

c = [a, b]

pprint_table(c)

输出:

^{pr2}$

你可以试试这个

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

来自http://docs.python.org/tutorial/inputoutput.html

:后面的整数是填充。在

或者更好

^{pr2}$

像这样:

labels = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 
    'place_effort']
values = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']

paddedLabels = []
paddedValues = []

for label, value in zip(labels, values):
    value = str(value)
    columnWidth = max(len(label), len(value))
    paddedLabels.append(label.center(columnWidth))
    paddedValues.append(value.center(columnWidth))

print ' '.join(paddedLabels)
print ' '.join(paddedValues)

输出:

^{pr2}$

如果你想变得花哨,就让它reStructuredText-准备就绪:

labels = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 
    'place_effort']
values = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']

paddedLabels = []
paddedValues = []
dividers = []
dblDividers = []

for label, value in zip(labels, values):
    value = str(value)
    columnWidth = max(len(label), len(value))
    paddedLabels.append(label.center(columnWidth))
    paddedValues.append(value.center(columnWidth))
    dividers.append('-' * columnWidth)
    dblDividers.append('=' * columnWidth)

print '+-' + '-+-'.join(dividers) + '-+'
print '| ' + ' | '.join(paddedLabels) + ' |'
print '+=' + '=+='.join(dblDividers) + '=+'
print '| ' + ' | '.join(paddedValues) + ' |'
print '+-' + '-+-'.join(dividers) + '-+'

输出:

+----+---------+-----------+------------+----------+-----------+--------------+
| id | Version | chip_name |  xversion  |  device  | opt_param | place_effort |
+====+=========+===========+============+==========+===========+==============+
| 1  |   1.0   |  virtex2  | xilinx11.5 | xc5vlx50 |   Speed   |     High     |
+----+---------+-----------+------------+----------+-----------+--------------+

相关问题 更多 >

    热门问题