漂亮的打印2D Python列表
有没有一种简单的内置方法可以将2D Python列表打印为2Dmatrix?
所以这:
[["A", "B"], ["C", "D"]]
会变成类似的东西
AB CD
我find了pprint模块,但似乎没有做我想要的。
为了让事情变得有趣,让我们尝试一个更大的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:对于多行单元,类似这样的应该工作:
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)
然后应用上面的代码。
如果您可以使用Pandas(Python数据分析库),则可以通过将其转换为DataFrame对象来美化打印2Dmatrix:
from pandas import * x = [["A", "B"], ["C", "D"]] print DataFrame(x) 0 1 0 AB 1 CD
你总是可以使用numpy
import numpy as np print(np.matrix(A))
比pandas
更轻量的方法是使用prettytable
模块
from prettytable import PrettyTable x = [["A", "B"], ["C", "D"]] p = PrettyTable() for row in x: p.add_row(row) print p.get_string(header=False, border=False)
收益率:
AB CD
prettytable
有很多选项来以不同的方式格式化你的输出。
有关更多信息,请参见https://code.google.com/p/prettytable/