from itertools import repeat def gen_table(rows, colfns=[], headings=[]): """ Pretty print a table, with optional headings, and return a string containing the table. Each column function will be called with the row number and should return the literal value to be printed. Args: rows - list of rows (if this value is large you should use xrange() ) colfns - column generator functions headings - list of headings to print, if None the heading row will not be printed Returns: A string containing the pretty printed table """ output = [] #column_lengths = list(repeat(0, len(colfns))) column_lengths = list(map(len, headings)) colidx = range(0, len(colfns)) for row in rows: # Get the value for each row # nb. call `tuple` to force immediate evaluation of the comprehension result = tuple( ( str(fn(row)) for fn in colfns ) ) # Compute the max length of each column column_lengths = [ max(column_lengths[i], curr_length) for i, curr_length in zip(colidx, map(len, result)) ] output.append(result) fmt = ' | '.join( ('{:>%d}' % (length) for length in column_lengths) ) header = '' if len(headings): header = fmt.format(*headings) + '\n' header += '-'*(len(header) -1) + '\n' return header + '\n'.join( (fmt.format(*line) for line in output) ) if __name__ == '__main__': as_binary = '{:b}'.format with_thousands_separator = '{:,d}'.format # TODO: need a nice way to use compose here, decorators require a # fn that returns an fn, so that will not play nicely with # format... def two_to_n(n): return with_thousands_separator(2**n) approx = lambda x: 2**(x%10) * 1000**(x//10) def pretty_print_approx(x): return with_thousands_separator(approx(x)) def base2_approx(x): return as_binary(approx(x)) delta = lambda x: 2**x - approx(x) def pretty_print_delta(x): return with_thousands_separator(delta(x)) def base2_delta(x): return as_binary(delta(x)) # Column functions, broken out for hackability colfns = [ str # used as identity here , two_to_n , pretty_print_approx , base2_approx , pretty_print_delta , base2_delta ] table = gen_table(range(1, 41), colfns=colfns, headings=['n', '2**n', 'approx', 'binary approx', 'delta', 'binary delta']) # For pythonfiddle.com print("<pre>\n") print(table)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question