【发布时间】:2013-11-08 16:01:27
【问题描述】:
我正在开发一个命令行解释器,我有一个函数可以以易于阅读的方式打印出一长串字符串。
函数是:
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 ... ....
【问题讨论】:
-
您可以将列数计算为
num_columns = len(list) // 100 + 2。这将为 100 提供 3 列,为 300 提供 5 列(同时仍然是线性函数)。 -
看起来你想要类似 [this answer].(stackoverflow.com/a/1524333/443348).
-
也许这对您的项目来说不是问题,但是您希望如何处理列表中非常宽的项目:
really-hairy-moldy-rotten-potato-with-cheese. -
@FMc,有趣的问题。这不会发生在我的项目中,但我需要注意的是 CL 上的打印输出整洁且易于阅读,因此也许将
really-hairy-moldy-rotten-potato-with-cheese放在它自己的最后一列中可能会起作用。或者在每个字符串之间放置一个分隔符,以便您轻松区分它们。
标签: python string printing command-line-interface