python教程—漂亮的打印2D Python列表-Python实用宝典

python教程—漂亮的打印2D Python列表

是否有一种简单的、内置的方法将2D Python列表打印为2D矩阵?这就变成了

是否有一种简单的、内置的方法将2D Python列表打印为2D矩阵?

所以这个:

    [["A", "B"], ["C", "D"]]

会变成

    A B C D

我找到了pprint模块,但它似乎没有做我想做的。

回答

为了让事情变得有趣,我们试着用一个更大的矩阵:

    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 havensome Camembert", "sir"], ["It's a bit", "runny", "sir"], ["Well,", "as a matternof fact it's", "very runny,nsir"], ["I think it'snrunnier", "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

​Python实用宝典 (pythondict.com)
不只是一个宝典
欢迎关注公众号:Python实用宝典

本文由 Python实用宝典 作者:Python实用宝典 发表,其版权均为 Python实用宝典 所有,文章内容系作者个人观点,不代表 Python实用宝典 对观点赞同或支持。如需转载,请注明文章来源。
0

发表评论