-
-
Save Nachtalb/8a85c0793b4bea0a102b7414be5888d4 to your computer and use it in GitHub Desktop.
Python: Multi-column printing of a list of strings
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
def col_print(lines, term_width=None, indent=0, pad=2): | |
"""Print list of strings in multiple columns | |
Original: https://gist.github.com/critiqjo/2ca84db26daaeb1715e1 | |
Adjusted: https://gist.github.com/Nachtalb/8a85c0793b4bea0a102b7414be5888d4 | |
""" | |
if not term_width: | |
size = shutil.get_terminal_size((80, 20)) | |
term_width = size.columns | |
n_lines = len(lines) | |
if n_lines == 0: | |
return | |
col_width = max(len(line) for line in lines) | |
n_cols = int((term_width + pad - indent) / (col_width + pad)) | |
n_cols = min(n_lines, max(1, n_cols)) | |
col_len = int(n_lines / n_cols) + (0 if n_lines % n_cols == 0 else 1) | |
if (n_cols - 1) * col_len >= n_lines: | |
n_cols -= 1 | |
cols = [lines[i * col_len: i * col_len + col_len] for i in range(n_cols)] | |
rows = list(zip(*cols)) | |
rows_missed = zip(*[col[len(rows):] for col in cols[:-1]]) | |
rows.extend(rows_missed) | |
for row in rows: | |
print(" " * indent + (" " * pad).join(line.ljust(col_width) for line in row)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment