一尘不染

漂亮的2D Python打印列表

python

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

所以这:

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

会变成像

A    B
C    D

我找到了pprint模块,但是它似乎并没有实现我想要的功能。


阅读 252

收藏
2021-01-20

共1个答案

一尘不染

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

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)

然后应用上面的代码。

另请参见http://pypi.python.org/pypi/texttable

2021-01-20