我对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循环,我已尝试打印为字符串。
我确信必须有一个非常简单的方法来做到这一点,但由于缺乏经验,我可能会错过它。
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))
一种简单的方法是遍历所有列,测量它们的宽度,为该最大宽度创建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
我会尝试遍历列表并使用CSV格式化程序来表示您想要的数据。
您可以将制表符,逗号或任何其他字符指定为分隔符。
否则,只需遍历列表并在每个元素后面打印“\ t”
我发现这只是寻找输出简单列的方法。如果你只需要没有烦恼的列,那么你可以使用这个:
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()
输出:
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
但这似乎不再比其他答案更简单了,可能还有它不需要更多进口的好处。但@ campkeith的答案已经满足并且更加强大,因为它可以处理更多种标签长度。
为此目的,有一些轻量级和有用的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,您可以控制水平/垂直对齐,边框样式和数据类型。
4.术语:https://github.com/nschloe/termtables
import termtables as tt
string = tt.to_string(
[["Alice", 24], ["Bob", 19]],
header=["Name", "Age"],
style=tt.styles.ascii_thin_double,
# alignment="ll",
# padding=(0, 1),
)
print(string)
+-------+-----+
| Name | Age |
+=======+=====+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
使用texttable,您可以控制水平/垂直对齐,边框样式和数据类型。
其他选择:
>>> 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
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
更新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))
当我这样做时,我喜欢控制表的格式化细节。特别是,我希望标题单元格具有与正文单元格不同的格式,并且表格列宽度只能与每个单元格所需的格式一样宽。这是我的解决方案:
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
纯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
以下函数将使用Python 3(也可能是Python 2)创建所请求的表(有或没有numpy)。我选择将每列的宽度设置为与最长的团队名称相匹配。如果您想使用每列的团队名称长度,您可以修改它,但会更复杂。
注意:对于Python 2中的直接等效项,您可以使用itertools中的zip
替换izip
。
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
。
参考文献: