我正在开发一个命令行解释器,我有一个函数,可以以一种易读的方式打印出一长串字符串。在
其功能是:
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))
因此,对于以下列表:
^{pr2}$函数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 ... ....
我有一个解决方案,它也将终端宽度作为输入,并且只显示可以容纳的列。参见:https://gist.github.com/critiqjo/2ca84db26daaeb1715e1
列_打印.py
从this answer修改。在
相关问题 更多 >
编程相关推荐