我对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循环,我尝试过打印字符串。

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


当前回答

我有个更好的,可以节省很多空间。

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

其他回答

一些特别的代码:

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))

这依赖于str.format()和格式规范迷你语言。

我有个更好的,可以节省很多空间。

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
>>> import pandas
>>> pandas.DataFrame(data, teams_list, teams_list)
           Man Utd  Man City  T Hotspur
Man Utd    1        2         1        
Man City   0        1         0        
T Hotspur  2        4         2        

对于简单的情况,你可以使用现代字符串格式(简化的Sven的答案): f ' {column1_value: 15} {column2_value}’:

table = {
    'Amplitude': [round(amplitude, 3), 'm³/h'],
    'MAE': [round(mae, 2), 'm³/h'],
    'MAPE': [round(mape, 2), '%'],
}

for metric, value in table.items():
    print(f'{metric:14} : {value[0]:>6.3f} {value[1]}')

输出:

Amplitude      :  1.438 m³/h
MAE            :  0.171 m³/h
MAPE           : 27.740 %

来源:https://docs.python.org/3/tutorial/inputoutput.html formatted-string-literals

我发现这只是为了寻找一种输出简单列的方法。如果你只是需要简单的列,那么你可以使用这个:

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的答案已经满足了这一点,并且更加健壮,因为它可以处理更广泛的标签长度。