Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

python - 漂亮的2D Python打印列表(Pretty print 2D Python list)

Is there a simple, built-in way to print a 2D Python list as a 2D matrix?

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

So this:

(所以这:)

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

would become something like

(会变成像)

A    B
C    D

I found the pprint module, but it doesn't seem to do what I want.

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

  ask by houbysoft translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = ''.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '
'.join(table)

Output:

(输出:)

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: for multiline cells, something like this should work:

(UPD:对于多行单元格,类似这样的方法应该起作用:)

text = [
    ["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"]
]

from itertools import chain, izip_longest

matrix = chain.from_iterable(
    izip_longest(
        *(x.splitlines() for x in y), 
        fillvalue='') 
    for y in text)

And then apply the above code.

(然后应用上面的代码。)

See also http://pypi.python.org/pypi/texttable

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...