def format_in_columns(elements, total_width=None, sep=" ", indent=" ", min_height=10):
"""
>>> print format_in_columns(map(str,range(100)), 50)
0 10 20 30 40 50 60 70 80 90
1 11 21 31 41 51 61 71 81 91
2 12 22 32 42 52 62 72 82 92
3 13 23 33 43 53 63 73 83 93
4 14 24 34 44 54 64 74 84 94
5 15 25 35 45 55 65 75 85 95
6 16 26 36 46 56 66 76 86 96
7 17 27 37 47 57 67 77 87 97
8 18 28 38 48 58 68 78 88 98
9 19 29 39 49 59 69 79 89 99
"""
if not total_width:
try:
total_width, _ = os.get_terminal_size()
except:
total_width = 80
widest = min(max(len(k) for k in elements), total_width)
columns = max((total_width - len(indent)) // (widest + len(sep)), 1)
height = max(min_height, (len(elements) // columns) + 1)
# arrange the elements in columns
columns = [[elem for (__, elem) in group]
for __, group in itertools.groupby(enumerate(elements), lambda p: p[0]//height)]
rows = itertools.zip_longest(*columns)
col_max = total_width - len(sep) * (len(columns) - 1)
column_lens = [min(max(map(len, column)), col_max) for column in columns]
return '\n'.join(indent + sep.join([(string or "").ljust(column_lens[column_num])
for column_num, string in enumerate(row)])
for row in rows)
评论列表
文章目录