简体   繁体   English

Python 漂亮的矩阵打印

[英]Python's pretty printing of matrix

I have to print several rows of data and do it good.我必须打印几行数据并做好。 I can do it with C++ changing parameters of std::cout, but I can't understand how I can do it with Python.我可以用 C++ 更改 std::cout 的参数来做到这一点,但我不明白我如何用 Python 做到这一点。 For example, I have this:例如,我有这个:

row1 = [1, 'arc1.tgz', 'First', '15.02.1992']
row2 = [16, 'arc2modified.tgz', 'Second', 'today']
row3 = ['112', 'arc89.tgz', 'Corrupted', 'unknown']

I want to print text like this:我想打印这样的文本:

1    arc1.tgz          First      15.02.1992
16   arc2modified.tgz  Second     today
112  arc89.tgz         Corrupted  unknown

It seems that it would be a clever idea to put it in one list and then count symbols in each string and then add spaces, but I'd like to know if there is more clever way to do it.似乎将它放在一个列表中然后计算每个字符串中的符号然后添加空格是一个聪明的主意,但我想知道是否有更聪明的方法来做到这一点。

The main problem is that I can use only default Python's modules.主要问题是我只能使用默认的 Python 模块。 Is there any possibility to do it?有没有可能做到? Thanks a lot!非常感谢!

my_matrix = [row1, row2, row3]
print "\n".join(["\t".join(map(str, r)) for r in my_matrix])

ETA: My original answer missed that you wanted each column to be of a fixed width, using padded spaces (rather than tabs). ETA:我最初的回答忽略了您希望每列具有固定宽度,使用填充空格(而不是制表符)。 It also looks like you want exactly two spaces between the longest datum and the next column.看起来您还希望最长数据和下一列之间正好有两个空格。 In that case, it can be done as follows (note that string is a built-in, default Python module):在这种情况下,可以按如下方式完成(注意string是一个内置的默认 Python 模块):

import string

max_lens = [max([len(str(r[i])) for r in my_matrix])
                for i in range(len(my_matrix[0]))]

print "\n".join(["".join([string.ljust(str(e), l + 2)
                for e, l in zip(r, max_lens)]) for r in my_matrix])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM