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)