如何将pretty print模块扩展到表中?

2024-06-01 20:29:46 发布

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

我有一个漂亮的print模块,我准备这个模块是因为我不高兴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]

代码如下:

^{pr2}$

以下是我的漂亮打印模块中用于表格打印的固定文本:

## 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 A simple Python library for easily displaying tabular data in a visually appealing ASCII table format


Tags: 模块代码in示例列表forprettyrange
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))

如果您正在寻找矩阵的良好格式,numpy的输出开箱即用非常好:

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

输出:

^{pr2}$

使用George Sakkis' table indention recipe

print(indent(((i + j for i in range(10)) for j in range(10)),
             delim=' ', justify='right'))

产量:

^{pr2}$

为了使以上的工作,我做了一个小的改变食谱。我将wrapfunc(item)改为wrapfunc(str(item))

def rowWrapper(row):
    newRows = [wrapfunc(str(item)).split('\n') for item in row]

相关问题 更多 >