3 ms·
You could probably do something a little simpler: widths = [len(max(col, key=len)) for col in zip(*table)] print("\n".join(" | ".join([f"{r:<{w}}" for r,
by robertlagrant 2y ago
You could probably do something a little simpler:
widths = [len(max(col, key=len)) for col in zip(*table)]
print("\n".join(" | ".join([f"{r:<{w}}" for r, w in zip(row, widths)]) for row in table))
# Gives:
# agony | kick | pump
# frown | lonely | mutation
# sail | tasty | want
- robertlagrant 2y agoFractionally more compact: widths = [max(map(len, col)) for col in zip(*table)] print("\n".join(" | ".join(f"{r:<{w}}" for r, w in zip(row, widths)) for row in table))
- bheadmaster 2y agoHa, clever. It didn't occur to me that I could use zip for extracting columns from a table. I personally prefer readable to compact, so this is what I ended up with, inspired by your version: tab_width = 4 columns = zip(*table) column_widths = [ max(len(item) for item in column) for column in columns ] column_indents = [ tab_width * ((width // tab_width) + 1) for width in column_widths ] for row in table: items = [ f'{item:<{indent}}' for item, indent in zip(row, column_indents) ] print(''.join(items).rstrip())
- robertlagrant 2y agoHah nice - yes I had it on three lines, which breaks out the logic a little better, but I thought it'd be good to just have a couple of lines to paste in and it would work. Someone elsewhere said they import pandas just to print a table! Surely overkill.