用 Python 打印漂亮的打印机?

发布于 2024-09-19 01:56:05 字数 2438 浏览 5 评论 0原文

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

['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')打印出每个元素。

但不幸的是,结果并不那么美好。

number of data 1 and number of column 7
id      Version     chip_name       xversion        device      opt_param       place_effort        
1       1.0     virtex2     xilinx11.5      xc5vlx50        Speed       High        

标签和数据的字符串长度变化很大,并且对齐得不好。

Python 有没有办法解决这个问题?

添加

在迈克·德西蒙(Mike DeSimone)的回答的帮助下,我可以制作出可以用于我的目的的漂亮打印机。 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     |
+----+---------+-----------+------------+----------+-----------+--------------+

感谢您的帮助。

I have a list of labels, and data as follows.

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

I need to print them into console. And for this, I'm iterating over the list, and print out each element with a tab ('\t').

But, unfortunately, the result is not so pretty.


number of data 1 and number of column 7
id      Version     chip_name       xversion        device      opt_param       place_effort        
1       1.0     virtex2     xilinx11.5      xc5vlx50        Speed       High        

The string length of label and data is quite variable, and it's not aligned well.

Is there any solution to this problem with Python?

ADDED

Hepled by Mike DeSimone's answer, I could make the pretty printer that I can use for my purposes. The valueResults are a list of duple.

    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'

And this is the result.


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

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

心凉怎暖 2024-09-26 01:56:05

在打印之前使用 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)

输出:

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

Use ljust to stuff the contents before they are printed out.

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)

output:

id     Version    chip_name      xversion      device    opt_param    place_effort 
1          1.0      virtex2    xilinx11.5    xc5vlx50        Speed            High
楠木可依 2024-09-26 01:56:05

像这样的东西:

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)

输出:

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

如果你想变得更奇特,请使其 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     |
+----+---------+-----------+------------+----------+-----------+--------------+

Something like this:

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)

Output:

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

If you want to get fancy, make it reStructuredText-ready:

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

Output:

+----+---------+-----------+------------+----------+-----------+--------------+
| id | Version | chip_name |  xversion  |  device  | opt_param | place_effort |
+====+=========+===========+============+==========+===========+==============+
| 1  |   1.0   |  virtex2  | xilinx11.5 | xc5vlx50 |   Speed   |     High     |
+----+---------+-----------+------------+----------+-----------+--------------+
枕头说它不想醒 2024-09-26 01:56:05

你可以

>>> 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

: 之后的整数是填充。

或者更好

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...        'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

you could try this

>>> 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

from http://docs.python.org/tutorial/inputoutput.html

The integer after the : is the padding.

or better yet

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...        'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
a√萤火虫的光℡ 2024-09-26 01:56:05

另一种解决方案是根本不使用制表符,并使用空格来调整列宽,也不需要手动填充,因为“%Ns”字符串格式很方便,例如

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

def print_row(row):
    column_width=12
    format_str = ("%-"+str(column_width)+"s")*len(row)
    print format_str%tuple(row)

print_row(header)
for row in rows:
    print_row(row)

输出:

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

Another solution is not to use tab at all, and uses spaces to adjust column width, also no need of manually padding, as '%Ns' string formatting comes handy e.g.

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

def print_row(row):
    column_width=12
    format_str = ("%-"+str(column_width)+"s")*len(row)
    print format_str%tuple(row)

print_row(header)
for row in rows:
    print_row(row)

Output:

id          Version     chip_name   xversion    device      opt_param   place_effort
1           1.0         virtex2     xilinx11.5  xc5vlx50    Speed       High
翻了热茶 2024-09-26 01:56:05

为了快速解决方案,如果 ln 是包含所有这些列表的列表,

for l in ln:
    print "\t".join([str(x).ljust(10) for x in l])

将打印由制表符分隔的列并左对齐。如果还不太漂亮,请增加 ljust 内的值。

For a quick solution, If ln is the list containing all these lists,

for l in ln:
    print "\t".join([str(x).ljust(10) for x in l])

will print columns seperated by tab and left-justified. Increase the value inside ljust if it isn't pretty yet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文