gpt4 book ai didi

python - pretty-print 二维列表?

转载 作者:IT老高 更新时间:2023-10-28 20:30:28 25 4
gpt4 key购买 nike

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

所以这个:

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

会变成这样的

A    B
C D

我找到了 pprint 模块,但它似乎没有做我想要的。

最佳答案

为了让事情变得有趣,让我们尝试一个更大的矩阵:

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)

输出:

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:对于多行单元格,这样的东西应该可以工作:

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)

然后应用上面的代码。

另见 http://pypi.python.org/pypi/texttable

关于python - pretty-print 二维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com