将列表打印为表格数据 [英] Printing Lists as Tabular Data

查看:51
本文介绍了将列表打印为表格数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am quite new to Python and I am now struggling with formatting my data nicely for printed output.

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

I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so:

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

请注意,标题名称的长度不一定相同.不过,数据条目都是整数.

Note that the heading names are not necessarily the same lengths. The data entries are all integers, though.

现在,我想以表格格式表示它,如下所示:

Now, I want to represent this in a table format, something like this:

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

我有一种预感,必须有一个用于此的数据结构,但我找不到它.我尝试过使用字典并格式化打印,我尝试过带缩进的 for 循环,我尝试过打印为字符串.

I have a hunch that there must be a data structure for this, but I cannot find it. I have tried using a dictionary and formatting the printing, I have tried for-loops with indentation and I have tried printing as strings.

我确信一定有一种非常简单的方法可以做到这一点,但由于缺乏经验,我可能错过了.

I am sure there must be a very simple way to do this, but I am probably missing it due to lack of experience.

推荐答案

一些临时代码:

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()格式规范迷你语言.

这篇关于将列表打印为表格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆