Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print 2D list?

Tags:

python

matrix

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

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.

like image 933
houbysoft Avatar asked Nov 04 '12 00:11

houbysoft


People also ask

How do you print a list in Python nicely?

Pass a list as an input to the print() function in Python. Use the asterisk operator * in front of the list to “unpack” the list into the print function. Use the sep argument to define how to separate two list elements visually.


2 Answers

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) 

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:

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) 

And then apply the above code.

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

like image 81
georg Avatar answered Sep 18 '22 09:09

georg


If you can use Pandas (Python Data Analysis Library) you can pretty-print a 2D matrix by converting it to a DataFrame object:

from pandas import * x = [["A", "B"], ["C", "D"]] print DataFrame(x)     0  1 0  A  B 1  C  D 
like image 22
sten Avatar answered Sep 19 '22 09:09

sten