Skip to content

Instantly share code, notes, and snippets.

@pinkie1378
Last active November 3, 2016 22:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pinkie1378/9accaca2caa5195823e3e3148047f9d5 to your computer and use it in GitHub Desktop.
Save pinkie1378/9accaca2caa5195823e3e3148047f9d5 to your computer and use it in GitHub Desktop.
3 different ways to format a table.
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]
@Sitwon
Copy link

Sitwon commented Nov 3, 2016

col_widths = [max(map(len, col)) for col in zip(*table)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment