我对Python很陌生,我现在正在努力为打印输出格式化我的数据。

我有一个用于两个标题的列表,以及一个应该是表的内容的矩阵。像这样:

teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = np.array([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])

注意,标题名称的长度不一定相同。但是,数据项都是整数。

现在,我想用表格的形式来表示,就像这样:

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2

我有一种预感,这一定有一个数据结构,但我找不到它。我尝试过使用字典和格式化打印,我尝试过使用缩进的for循环,我尝试过打印字符串。

我相信一定有一个非常简单的方法来做到这一点,但我可能因为缺乏经验而错过了它。


当前回答

将Sven Marnach的答案更新到Python 3.4中:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

其他回答

下面的函数将使用Python 3(也可能是Python 2)创建所请求的表(带或不带numpy)。我已经选择将每个列的宽度设置为与最长的球队名匹配。如果您希望为每一列使用球队名称的长度,则可以对其进行修改,但这将更加复杂。

注意:在Python 2中,你可以用itertools中的izip替换zip。

def print_results_table(data, teams_list):
    str_l = max(len(t) for t in teams_list)
    print(" ".join(['{:>{length}s}'.format(t, length = str_l) for t in [" "] + teams_list]))
    for t, row in zip(teams_list, data):
        print(" ".join(['{:>{length}s}'.format(str(x), length = str_l) for x in [t] + row]))

teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = [[1, 2, 1],
        [0, 1, 0],
        [2, 4, 2]]

print_results_table(data, teams_list)

这将产生以下表格:

            Man Utd  Man City T Hotspur
  Man Utd         1         2         1
 Man City         0         1         0
T Hotspur         2         4         2

如果你想要有垂直的线分隔符,你可以替换“”。加入" | ". Join。

引用:

很多关于格式https://pyformat.info/(旧的和新的格式 风格) 官方的Python教程(相当不错)- https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method 官方的Python信息(可能很难阅读)- https://docs.python.org/3/library/string.html#string-formatting 另一种资源—— https://www.python-course.eu/python3_formatted_output.php

一种简单的方法是遍历所有列,测量它们的宽度,为最大宽度创建一个row_template,然后打印行。这并不是你想要的,因为在这种情况下,你首先要把你的标题放在表格中,但我认为它可能对其他人有用。

table = [
    ["", "Man Utd", "Man City", "T Hotspur"],
    ["Man Utd", 1, 0, 0],
    ["Man City", 1, 1, 0],
    ["T Hotspur", 0, 1, 2],
]
def print_table(table):
    longest_cols = [
        (max([len(str(row[i])) for row in table]) + 3)
        for i in range(len(table[0]))
    ]
    row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row))

你可以这样使用它:

>>> print_table(table)

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2
table_data= [[1,2,3],[4,5,6],[7,8,9]]

for row in table_data:
    print("{: >20} {: >20} {: >20}".format(*row))

输出:

               1                  2                3
               4                  5                6
               7                  8                9

其中f字符串格式化

“>”用于右对齐 "<"用于左对齐

20为空间宽度,可根据需要进行调整。

将Sven Marnach的答案更新到Python 3.4中:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

我会尝试遍历列表,并使用CSV格式化器来表示所需的数据。

您可以指定制表符、逗号或任何其他字符作为分隔符。

否则,只需遍历列表并在每个元素后打印“\t”

http://docs.python.org/library/csv.html