python - 将列表打印为表格D.
我对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循环,我已尝试打印为字符串。
我确信必须有一个非常简单的方法来做到这一点,但由于缺乏经验,我可能会错过它。
hjweide asked 2019-03-09T12:05:34Z
12个解决方案
338 votes
为此目的,有一些轻量级和有用的python包:
制表:[https://pypi.python.org/pypi/tabulate]
>>> from tabulate import tabulate
>>> print tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'])
Name Age
------ -----
Alice 24
Bob 19
tabulate有许多选项来指定标题和表格格式。
>>> print tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl')
| Name | Age |
|--------+-------|
| Alice | 24 |
| Bob | 19 |
2. PrettyTable:[https://pypi.python.org/pypi/PrettyTable]
>>> from prettytable import PrettyTable
>>> t = PrettyTable(['Name', 'Age'])
>>> t.add_row(['Alice', 24])
>>> t.add_row(['Bob', 19])
>>> print t
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
| Bob | 19 |
+-------+-----+
PrettyTable有从csv,html,sql数据库读取数据的选项。 您还可以选择数据子集,排序表和更改表格样式。
3. texttable:[https://pypi.python.org/pypi/texttable]
>>> from texttable import Texttable
>>> t = Texttable()
>>> t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
>>> print t.draw()
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
使用texttable,您可以控制水平/垂直对齐,边框样式和数据类型。
其他选择:
terminaltables从字符串列表列表中轻松绘制终端/控制台应用程序中的表。 支持多行行。
asciitable Asciitable可以通过内置的Extension Reader Classes读写各种ASCII表格格式。
iman answered 2019-03-09T12:08:52Z
141 votes
Python 2.7的一些特殊代码:
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()和格式规范迷你语言。
Sven Marnach answered 2019-03-09T12:06:08Z
58 votes
>>> 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
jfs answered 2019-03-09T12:09:12Z
40 votes
Python实际上使这很容易。
就像是
for i in range(10):
print '%-12i%-12i' % (10 ** i, 20 ** i)
将有输出
1 1
10 20
100 400
1000 8000
10000 160000
100000 3200000
1000000 64000000
10000000 1280000000
100000000 25600000000
1000000000 512000000000
字符串中的%本质上是一个转义字符,后面的字符告诉python数据应该具有什么样的格式。 字符串外部和后面的%告诉python您打算使用前一个字符串作为格式字符串,并且应将以下数据放入指定的格式。
在这种情况下,我使用了“%-12i”两次。 分解每个部分:
'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)
来自文档:[https://docs.python.org/2/library/stdtypes.html#string-formatting]
Austin answered 2019-03-09T12:10:51Z
24 votes
BeautifulTable和Tabulate是您可以用来解决问题的众多软件包中的一部分。
以下是来自beautifultable文档的示例
>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.column_headers = ["name", "rank", "gender"]
>>> table.append_row(["Jacob", 1, "boy"])
>>> table.append_row(["Isabella", 1, "girl"])
>>> table.append_row(["Ethan", 2, "boy"])
>>> table.append_row(["Sophia", 2, "girl"])
>>> table.append_row(["Michael", 3, "boy"])
>>> print(table)
+----------+------+--------+
| name | rank | gender |
+----------+------+--------+
| Jacob | 1 | boy |
+----------+------+--------+
| Isabella | 1 | girl |
+----------+------+--------+
| Ethan | 2 | boy |
+----------+------+--------+
| Sophia | 2 | girl |
+----------+------+--------+
| Michael | 3 | boy |
+----------+------+--------+
Priyam Singh answered 2019-03-09T12:11:38Z
12 votes
更新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))
SmrtGrunt answered 2019-03-09T12:12:12Z
8 votes
我想这就是你要找的东西。
这是一个简单的模块,它只计算表条目所需的最大宽度,然后只使用rjust和ljust来完成数据的漂亮打印。
如果您希望左侧标题右对齐,只需更改此调用:
print >> out, row[0].ljust(col_paddings[0] + 1),
从第53行到:
print >> out, row[0].rjust(col_paddings[0] + 1),
Bogdan answered 2019-03-09T12:13:25Z
8 votes
当我这样做时,我喜欢控制表的格式化细节。 特别是,我希望标题单元格具有与正文单元格不同的格式,并且表格列宽度只能与每个单元格所需的格式一样宽。 这是我的解决方案:
def format_matrix(header, matrix,
top_format, left_format, cell_format, row_delim, col_delim):
table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
table_format = [['{:^{}}'] + len(header) * [top_format]] \
+ len(matrix) * [[left_format] + len(header) * [cell_format]]
col_widths = [max(
len(format.format(cell, 0))
for format, cell in zip(col_format, col))
for col_format, col in zip(zip(*table_format), zip(*table))]
return row_delim.join(
col_delim.join(
format.format(cell, width)
for format, cell, width in zip(row_format, row, col_widths))
for row_format, row in zip(table_format, table))
print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
[[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
'{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')
这是输出:
| Man Utd | Man City | T Hotspur | Really Long Column
Man Utd | 1.000 | 2.000 | 1.000 | -1.000
Man City | 0.000 | 1.000 | 0.000 | 5.000
T Hotspur | 2.000 | 4.000 | 2.000 | 2.000
Really Long Column | 0.000 | 1.000 | 0.000 | 6.000
campkeith answered 2019-03-09T12:13:56Z
3 votes
纯Python 3
def print_table(data, cols, wide):
'''Prints formatted data on columns of given width.'''
n, r = divmod(len(data), cols)
pat = '{{:{}}}'.format(wide)
line = '\n'.join(pat * cols for _ in range(n))
last_line = pat * r
print(line.format(*data))
print(last_line.format(*data[n*cols:]))
data = [str(i) for i in range(27)]
print_table(data, 6, 12)
会打印
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
24 25 26
The Data Scientician answered 2019-03-09T12:14:31Z
2 votes
我会尝试遍历列表并使用CSV格式化程序来表示您想要的数据。
您可以将制表符,逗号或任何其他字符指定为分隔符。
否则,只需遍历列表并在每个元素后面打印“\ t”
[http://docs.python.org/library/csv.html]
Jeffrey Kevin Pry answered 2019-03-09T12:15:22Z
1 votes
一种简单的方法是遍历所有列,测量它们的宽度,为该最大宽度创建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
Emil Stenström answered 2019-03-09T12:16:36Z
0 votes
以下函数将使用Python 3(也可能是Python 2)创建所请求的表(有或没有numpy)。 我选择将每列的宽度设置为与最长的团队名称相匹配。 如果您想使用每列的团队名称长度,您可以修改它,但会更复杂。
注意:对于Python 2中的直接等效项,您可以从itertools替换" ".join和" | ".join。
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替换为" | ".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]
Diomedea answered 2019-03-09T12:19:46Z