Để thực hiện những điều thú vị, chúng ta hãy thử với một ma trận lớn hơn:
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: cho tế bào multiline, một cái gì đó như thế này nên làm việc:
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)
Và sau đó áp dụng mã trên.
Xem thêm http://pypi.python.org/pypi/texttable
Tôi đã gọi đó là danh sách 3D. Nếu bạn sẵn sàng để kéo nó vào, 'numpy' là khá tốt về loại điều này. – tacaswell
@tcaswell: Rất tiếc, đúng. Tôi chỉ muốn nó được coi là ma trận 2D. Đã thay đổi câu hỏi để làm cho thiên tài rõ ràng là – houbysoft