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

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


当前回答

要使用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)

其他回答

尝试丰富:https://github.com/Textualize/rich

from rich.console import Console
from rich.table import Table

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
    "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)

https://github.com/willmcgugan/rich/raw/master/imgs/table.png

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

Pure 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
table_data= [[1,2,3],[4,5,6],[7,8,9]]

for row in table_data:
    print("{: >20} {: >20} {: >20}".format(*row))

输出:

               1                  2                3
               4                  5                6
               7                  8                9

其中f字符串格式化

“>”用于右对齐 "<"用于左对齐

20为空间宽度,可根据需要进行调整。

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