python - How to extend pretty print module to tables? -
i have pretty print module, prepared because not happy pprint module produced zillion lines list of numbers had 1 list of list. here example use of module.
>>> a=range(10) >>> a.insert(5,[range(i) in range(10)]) >>> [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]
code this:
""" pretty.py prettyprint module version alpha 0.2 mypr: pretty string function ppr: print of pretty string list , tuple prettying implemented! """ def mypr(w, = 0, indent = 2, nl = '\n') : """ w = datastructure, = indent level, indent = step size indention """ startend = {list : '[]', tuple : '()'} if type(w) in (list, tuple) : start, end = startend[type(w)] pr = [mypr(j, + indent, indent, nl) j in w] return nl + ' ' * + start + ', '.join(pr) + end else : return repr(w) def ppr(w, = 0, indent = 2, nl = '\n') : """ see mypr, print of mypr same parameters """ print mypr(w, i, indent, nl)
here 1 fixed text table printing in pretty print module:
## let's "manually" width = len(str(10+10)) widthformat = '%'+str(width)+'i' in range(10): j in range(10): print widthformat % (i+j), print
have better alternative code generalized enough pretty printing module?
what found kind of regular cases after posting question module: prettytable simple python library displaying tabular data in visually appealing ascii table format
if you're looking nice formatting matrices, numpy's output looks great right out of box:
from numpy import * print array([[i + j in range(10)] j in range(10)])
output:
[[ 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]]
Comments
Post a Comment