本文介绍了漂亮的2D Python打印列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的内置方法将2D Python列表打印为2D矩阵?
Is there a simple, built-in way to print a 2D Python list as a 2D matrix?
所以这个:
[["A", "B"], ["C", "D"]]
会变成类似
A B
C D
我找到了pprint模块,但是它似乎并没有满足我的要求.
I found the pprint module, but it doesn't seem to do what I want.
推荐答案
为了使事情有趣,让我们尝试使用更大的矩阵:
To make things interesting, let's try with a bigger matrix:
matrix = [
["Ah!", "We do have some Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter of fact it's", "very runny, sir"],
["I think it's runnier", "than you", "like it, sir"]
]
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)
输出:
Ah! We do have some Camembert sir
It's a bit runny sir
Well, as a matter of fact it's very runny, sir
I think it's runnier than you like it, sir
UPD:对于多行单元格,这样的方法应该起作用:
UPD: for multiline cells, something like this should work:
text = [
["Ah!", "We do have\nsome Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter\nof fact it's", "very runny,\nsir"],
["I think it's\nrunnier", "than you", "like it,\nsir"]
]
from itertools import chain, izip_longest
matrix = chain.from_iterable(
izip_longest(
*(x.splitlines() for x in y),
fillvalue='')
for y in text)
然后应用上面的代码.
另请参见 http://pypi.python.org/pypi/texttable
这篇关于漂亮的2D Python打印列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!