我对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循环,我尝试过打印字符串。
我相信一定有一个非常简单的方法来做到这一点,但我可能因为缺乏经验而错过了它。
一种简单的方法是遍历所有列,测量它们的宽度,为最大宽度创建一个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 = [
['number1', 'x', 'name'],
["4x", "3", "Hi"],
["2", "1", "808890312093"],
["5", "Hi", "Bye"]
]
column_max_width = [max(len(row[column_index]) for row in table) for column_index in range(len(table[0]))]
row_format = ["{:>"+str(width)+"}" for width in column_max_width]
for row in table:
print("|".join([print_format.format(value) for print_format, value in zip(row_format, row)]))
输出:
number1| x| name
4x| 3| Hi
2| 1|808890312093
5|Hi| Bye
我发现这只是为了寻找一种输出简单列的方法。如果你只是需要简单的列,那么你可以使用这个:
print("Titlex\tTitley\tTitlez")
for x, y, z in data:
print(x, "\t", y, "\t", z)
编辑:我试图尽可能简单,因此手动做了一些事情,而不是使用团队列表。概括一下OP的实际问题:
#Column headers
print("", end="\t")
for team in teams_list:
print(" ", team, end="")
print()
# rows
for team, row in enumerate(data):
teamlabel = teams_list[team]
while len(teamlabel) < 9:
teamlabel = " " + teamlabel
print(teamlabel, end="\t")
for entry in row:
print(entry, end="\t")
print()
Ouputs:
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
但这似乎不再比其他答案简单,好处可能是它不需要更多的进口。但是@campkeith的答案已经满足了这一点,并且更加健壮,因为它可以处理更广泛的标签长度。