我有三个列表:
alist=[1,2,3,4,5]
blist=['a','b','c','d','e']
clist=['@','#','$','&','*']
我想要这种格式的输出:
1 2 3 4 5
a b c d e
@ # $ & *
我能够以正确的格式打印,但是当我有包含许多元素的列表时,它实际上是这样打印的:
1 2 3 4 5 6 ..........................................................................
................................................................................
a b c d e ............................................................................
......................................................................................
@ # $ & * .............................................................................
.......................................................................................
但我希望我的输出是这样的:
12345....................................................................
abcde...................................................................
@#$&*...................................................................
............................................................... {this line is from alist}
................................................................ {this line is from blist}
................................................................ {this line is from clist}
请您参考如下方法:
尝试以下操作:
term_width = 80
all_lists = (alist, blist, clist)
length = max(map(len, all_lists))
for offset in xrange(0, length, term_width):
print '\n'.join(''.join(map(str, l[offset:offset+term_width])) for l in all_lists)
这假设终端宽度为 80 个字符,这是默认值。您可能想使用 curses 库或基于它的东西来检测它的实际宽度。
无论哪种方式,要适应任何输出宽度,您只需更改 term_width 值,代码就会使用它。
它还假定所有元素的长度都是 1 个字符。如果不是这样,请澄清。
如果你需要检测终端宽度,你可以在这里找到一些解决方案:How to get Linux console window width in Python
