3 ms·
from itertools import zip_longest tab_width = 4 col_max_widths = [(v := max(map(len, a))) + tab_width - (v % tab_width) for a
by deno 2y ago
from itertools import zip_longest
tab_width = 4
col_max_widths = [(v := max(map(len, a))) + tab_width - (v % tab_width)
for a in zip_longest(*table, fillvalue='')]
for row in table:
print(''.join(c.ljust(cw) for cw, c in zip(col_max_widths, row)))
- bheadmaster 2y agoIsn't zip_longest only useful for zipping sequences of different lengths? What exactly is it doing here that couldn't be done with plain zip? Also that code (IMHO, of course) still gives me a headache when I try to mentally parse it.
- deno 2y agoRegular zip works, I just don’t like the worst case because if one row has fewer columns the entire column will be quietly dropped since builtin zip works as zip_shortest rather than raise an exception. I never use bultin zip on input data.