Last active
November 3, 2016 22:22
-
-
Save pinkie1378/9accaca2caa5195823e3e3148047f9d5 to your computer and use it in GitHub Desktop.
3 different ways to format a table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import starmap | |
def format_table(table, delim='|'): | |
""" | |
:param list table: 2D list, with inner lists of strings as rows. | |
:param str delim: Used to define table cell borders. | |
:return list: Containing formatted string elements representing each row, | |
ready to be written to a file. | |
""" | |
assert len(set(len(row) for row in table)) == 1, "'table' param has rows of differing lengths" | |
col_widths = [len(max(col, key=len)) for col in zip(*table)] | |
left_justify = lambda cell, width: '{{:<{}}}'.format(width).format(cell) | |
justify_cells = lambda cells: starmap(left_justify, zip(cells, col_widths)) | |
make_row = lambda cells: ' {} '.format(delim).join(justify_cells(cells)) | |
make_line = lambda cells: '{0} {1} {0}\n'.format(delim, make_row(cells)) | |
return [make_line(row) for row in table] | |
def format_table_with_map(table, delim='|'): | |
col_widths = [len(max(col, key=len)) for col in zip(*table)] | |
rows_with_widths = map(lambda row: zip(row, col_widths), table) | |
justified_cells = map( | |
lambda row: starmap(lambda cell, width: '{{:<{}}}'.format(width).format(cell), row), | |
rows_with_widths) | |
joined_rows = map(lambda row: ' {} '.format(delim).join(row), justified_cells) | |
return list(map(lambda row: '{0} {1} {0}\n'.format(delim, row), joined_rows)) | |
def format_table_list_comp(table, delim='|'): | |
col_widths = [len(max(col, key=len)) for col in zip(*table)] | |
padded_delim = ' {} '.format(delim) | |
left_justify = lambda cell, width: '{{:<{}}}'.format(width).format(cell) | |
return [ | |
'{0} {1} {0}\n'.format( | |
delim, | |
padded_delim.join([left_justify(cell, width) for cell, width in zip(row, col_widths)])) | |
for row in table | |
] | |
def format_table_pythonic(table, delim='|'): | |
col_widths = [max(map(len, col)) for col in zip(*table)] | |
left_justified_cell_templates = [' {:<%d} ' % width for width in col_widths] | |
row_template = '{0}{1}{0}\n'.format(delim, delim.join(left_justified_cell_templates)) | |
return [row_template.format(*row) for row in table] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
col_widths = [max(map(len, col)) for col in zip(*table)]