Created
June 16, 2015 07:50
-
-
Save critiqjo/2ca84db26daaeb1715e1 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=80, indent=0, pad=2): | |
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
You could add console size detection so that it is a bit more dynamic.