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

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


当前回答

我觉得这就是你要找的东西。

这是一个简单的模块,它只是计算表项所需的最大宽度,然后使用rjust和ljust来打印数据。

如果你想让你的左标题右对齐,只需改变这个调用:

 print >> out, row[0].ljust(col_paddings[0] + 1),

从第53行开始

 print >> out, row[0].rjust(col_paddings[0] + 1),

其他回答

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

有一些简单而有用的python包用于此目的:

1. 汇总: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  |
+-------+-----+

通过文本表,你可以控制水平/垂直对齐,边框样式和数据类型。

4. termtables: 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  |
+-------+-----+

通过文本表,你可以控制水平/垂直对齐,边框样式和数据类型。

其他选项:

在终端/控制台应用程序中,很容易从字符串的列表中绘制表格。支持多行。 asciitable可以通过内置的扩展阅读器类读取和写入广泛的ASCII表格式。

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

我知道我迟到了,但我刚刚为这个做了一个库,我认为它真的很有帮助。它非常简单,这就是为什么我认为你应该使用它。它叫做TableIT。

基本的使用

要使用它,首先要遵循GitHub页面上的下载说明。

然后导入:

import TableIt

然后创建一个列表的列表,其中每个内列表都是一行:

table = [
    [4, 3, "Hi"],
    [2, 1, 808890312093],
    [5, "Hi", "Bye"]
]

然后你要做的就是打印它:

TableIt.printTable(table)

这是你得到的输出:

+--------------------------------------------+
| 4            | 3            | Hi           |
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

字段名称

如果你愿意,你可以使用字段名(如果你不使用字段名,你不必说useFieldNames=False,因为它是默认设置的):


TableIt.printTable(table, useFieldNames=True)

从中你会得到:

+--------------------------------------------+
| 4            | 3            | Hi           |
+--------------+--------------+--------------+
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

还有其他用途,比如你可以这样做:

import TableIt

myList = [
    ["Name", "Email"],
    ["Richard", "richard@fakeemail.com"],
    ["Tasha", "tash@fakeemail.com"]
]

TableIt.print(myList, useFieldNames=True)

来自:

+-----------------------------------------------+
| Name                  | Email                 |
+-----------------------+-----------------------+
| Richard               | richard@fakeemail.com |
| Tasha                 | tash@fakeemail.com    |
+-----------------------------------------------+

或者你可以这样做:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True)

从中你可以得到:

+-----------------------+
|       | a     | b     |
+-------+-------+-------+
| x     | a + x | a + b |
| z     | a + z | z + b |
+-----------------------+

颜色

你也可以使用颜色。

您可以使用color选项(默认设置为None)并指定RGB值来使用颜色。

使用上面的例子:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True, color=(26, 156, 171))

那么你会得到:

请注意,打印颜色可能不适合你,但它的工作原理与其他打印彩色文本的库完全相同。我已经测试过了,每一种颜色都可以。如果使用默认的34m ANSI转义序列,蓝色也不会被打乱(如果你不知道那是什么,没关系)。不管怎样,这都是因为每个颜色都是RGB值,而不是系统默认值。

更多信息

欲了解更多信息,请查看GitHub页面

当我这样做时,我喜欢对表格的格式细节有一定的控制。特别是,我希望标题单元格与主体单元格具有不同的格式,并且表列的宽度仅为每个列所需的宽度。以下是我的解决方案:

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