我正在使用命令行解释器,我有一个以易于阅读的方式打印出一长串字符串的函数。
功能是:
def pretty_print(CL_output):
if len(CL_output)%2 == 0:
#even
print "\n".join("%-20s %s"%(CL_output[i],CL_output[i+len(CL_output)/2]) for i in range(len(CL_output)/2))
else:
#odd
d_odd = CL_output + ['']
print "\n".join("%-20s %s"%(d_odd[i],d_odd[i+len(d_odd)/2]) for i in range(len(d_odd)/2))
因此,对于如下列表:
myList = ['one','potato','two','potato','three','potato','four','potato'...]
函数pretty_print返回:
pretty_print(myList)
>>> one three
potato potato
two four
potato potato
但是对于更大的列表,函数pretty_print仍会在两列中打印出列表。有没有办法修改pretty_print,以便根据列表的大小打印出3或4列的列表?所以len(myList)~100,pretty_print将打印出3行,而len(myList)~300,pretty_print将打印出4列。
所以,如果我有:
myList_long = ['one','potato','two','potato','three','potato','four','potato'...
'one hundred`, potato ...... `three hundred`,potato]
所需的输出是:
pretty_print(myList_long)
>>> one three one hundred three hundred
potato potato potato potato
two four ... ...
potato potato ... ....
答案 0 :(得分:2)
从this answer修改。
def pretty_print(CL_output):
columns = len(CL_output)//200+2
lines = ("".join(s.ljust(20) for s in CL_output[i:i+columns-1])+CL_output[i:i+columns][-1] for i in range(0, len(CL_output), columns))
return "\n".join(lines)
答案 1 :(得分:0)
我有一个解决方案,它也将终端宽度作为输入,只显示可以容纳的列数。请参阅:https://gist.github.com/critiqjo/2ca84db26daaeb1715e1
<强> col_print.py 强>
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))