我准备了一个漂亮的打印模块,因为我不喜欢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 A simple Python library for easily displaying tabular data in a visually appealing ASCII table format
4条答案
按热度按时间ctehm74n1#
如果您希望为矩阵设置良好的格式,numpy的输出看起来非常棒:
输出:
jw5wzhpr2#
你可以写:
bvjxkvbb3#
使用George Sakkis' table indention recipe:
产量:
PS.为了让上面的工作正常进行,我对食谱做了一个小改动。我把
wrapfunc(item)
改成了wrapfunc(str(item))
:kr98yfug4#
我对这类常见情况的回答是使用以下模块:prettytable A simple Python library for easily displaying tabular data in a visually appealing ASCII table format