Is there a simple, built-in way to print a 2D Python list as a 2D matrix?
So this:
JavaScript
x
2
1
[["A", "B"], ["C", "D"]]
2
would become something like
JavaScript
1
3
1
A B
2
C D
3
I found the pprint
module, but it doesn’t seem to do what I want.
Advertisement
Answer
To make things interesting, let’s try with a bigger matrix:
JavaScript
1
13
13
1
matrix = [
2
["Ah!", "We do have some Camembert", "sir"],
3
["It's a bit", "runny", "sir"],
4
["Well,", "as a matter of fact it's", "very runny, sir"],
5
["I think it's runnier", "than you", "like it, sir"]
6
]
7
8
s = [[str(e) for e in row] for row in matrix]
9
lens = [max(map(len, col)) for col in zip(*s)]
10
fmt = 't'.join('{{:{}}}'.format(x) for x in lens)
11
table = [fmt.format(*row) for row in s]
12
print 'n'.join(table)
13
Output:
JavaScript
1
5
1
Ah! We do have some Camembert sir
2
It's a bit runny sir
3
Well, as a matter of fact it's very runny, sir
4
I think it's runnier than you like it, sir
5
UPD: for multiline cells, something like this should work:
JavaScript
1
15
15
1
text = [
2
["Ah!", "We do havensome Camembert", "sir"],
3
["It's a bit", "runny", "sir"],
4
["Well,", "as a matternof fact it's", "very runny,nsir"],
5
["I think it'snrunnier", "than you", "like it,nsir"]
6
]
7
8
from itertools import chain, izip_longest
9
10
matrix = chain.from_iterable(
11
izip_longest(
12
*(x.splitlines() for x in y),
13
fillvalue='')
14
for y in text)
15
And then apply the above code.