如何扩展美化打印模块以支持表格?

-1 投票
4 回答
1708 浏览
提问于 2025-04-16 01:44

我有一个漂亮打印模块,这是我自己准备的,因为我对pprint模块输出的结果不满意。它会为一个包含列表的列表的数字生成很多行。下面是我这个模块的一个使用示例。

    >>> a=range(10)
    >>> a.insert(5,[range(i) for i in range(10)])
    >>> a
    [0, 1, 2, 3, 4, [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]
    >>> import pretty
    >>> pretty.ppr(a,indent=6)

    [0, 1, 2, 3, 4, 
          [
            [], 
            [0], 
            [0, 1], 
            [0, 1, 2], 
            [0, 1, 2, 3], 
            [0, 1, 2, 3, 4], 
            [0, 1, 2, 3, 4, 5], 
            [0, 1, 2, 3, 4, 5, 6], 
            [0, 1, 2, 3, 4, 5, 6, 7], 
            [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]

代码大致是这样的:

""" pretty.py prettyprint module version alpha 0.2
    mypr: pretty string function
    ppr:  print of the pretty string
    ONLY list and tuple prettying implemented!
"""
def mypr(w, i = 0, indent = 2, nl = '\n') :
    """ w = datastructure, i = indent level, indent = step size for indention """
    startend = {list : '[]', tuple : '()'}
    if type(w) in (list, tuple) :
        start, end = startend[type(w)]
        pr = [mypr(j, i + indent, indent, nl) for j in w]
        return nl + ' ' * i + start + ', '.join(pr) + end
    else :  return repr(w)

def ppr(w, i = 0, indent = 2, nl = '\n') :
    """ see mypr, this is only print of mypr with same parameters """
    print mypr(w, i, indent, nl)

这是我在漂亮打印模块中用于表格打印的一段固定文本:

## let's do it "manually"
width = len(str(10+10))
widthformat = '%'+str(width)+'i'
for i in range(10):
    for j in range(10):
        print widthformat % (i+j),
    print

你有没有更好的方法,可以让这个代码更通用,适用于漂亮打印模块呢?

在我发布这个问题后,我发现了一个模块:prettytable,一个简单的Python库,可以轻松地以美观的ASCII表格格式显示表格数据

4 个回答

3

你可以这样写:

'\n'.join(  # join the lines with '\n'
       ' '.join(  # join one line with ' '
              "%2d" % (i + j) # format each item
        for i in range(10))
    for j in range(10))
7

如果你想要漂亮的矩阵格式,numpy的输出效果非常好,直接使用就可以了:

from numpy import *
print array([[i + j for i in range(10)] for j in range(10)])

输出结果:

[[ 0  1  2  3  4  5  6  7  8  9]
 [ 1  2  3  4  5  6  7  8  9 10]
 [ 2  3  4  5  6  7  8  9 10 11]
 [ 3  4  5  6  7  8  9 10 11 12]
 [ 4  5  6  7  8  9 10 11 12 13]
 [ 5  6  7  8  9 10 11 12 13 14]
 [ 6  7  8  9 10 11 12 13 14 15]
 [ 7  8  9 10 11 12 13 14 15 16]
 [ 8  9 10 11 12 13 14 15 16 17]
 [ 9 10 11 12 13 14 15 16 17 18]]

撰写回答