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

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


当前回答

我会尝试遍历列表,并使用CSV格式化器来表示所需的数据。

您可以指定制表符、逗号或任何其他字符作为分隔符。

否则,只需遍历列表并在每个元素后打印“\t”

http://docs.python.org/library/csv.html

其他回答

对于简单的情况,你可以使用现代字符串格式(简化的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

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

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实际上让这变得非常简单。

类似的

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

就用它吧

from beautifultable import BeautifulTable

table = BeautifulTable()
table.column_headers = ["", "Man Utd","Man City","T Hotspur"]
table.append_row(['Man Utd',  1,  2,  3])
table.append_row(['Man City', 7, 4,  1])
table.append_row(['T Hotspur', 3, 2,  2])
print(table)

这样,你就得到了一个整洁的表格。

要使用terminaltables创建一个简单的表,打开终端或命令提示符并运行pip install terminaltables。

你可以像下面这样打印Python列表:

from terminaltables import AsciiTable

l = [
  ['Head', 'Head'],
  ['R1 C1', 'R1 C2'],
  ['R2 C1', 'R2 C2'],
  ['R3 C1', 'R3 C2']
]

table = AsciiTable(l)
print(table.table)