我对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),

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

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

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

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


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

一些特别的代码:

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()和格式规范迷你语言。


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


有一些简单而有用的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表格式。


将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

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

下面的函数将使用Python 3(也可能是Python 2)创建所请求的表(带或不带numpy)。我已经选择将每个列的宽度设置为与最长的球队名匹配。如果您希望为每一列使用球队名称的长度,则可以对其进行修改,但这将更加复杂。

注意:在Python 2中,你可以用itertools中的izip替换zip。

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。

引用:

很多关于格式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


一种简单的方法是遍历所有列,测量它们的宽度,为最大宽度创建一个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

我发现这只是为了寻找一种输出简单列的方法。如果你只是需要简单的列,那么你可以使用这个:

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

Ouputs:

          Man Utd  Man City  T Hotspur
  Man Utd       1       2       1   
 Man City       0       1       0   
T Hotspur       2       4       2   

但这似乎不再比其他答案简单,好处可能是它不需要更多的进口。但是@campkeith的答案已经满足了这一点,并且更加健壮,因为它可以处理更广泛的标签长度。


我知道我迟到了,但我刚刚为这个做了一个库,我认为它真的很有帮助。它非常简单,这就是为什么我认为你应该使用它。它叫做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页面


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

就用它吧

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)

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


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


我有个更好的,可以节省很多空间。

table = [
    ['number1', 'x', 'name'],
    ["4x", "3", "Hi"],
    ["2", "1", "808890312093"],
    ["5", "Hi", "Bye"]
]
column_max_width = [max(len(row[column_index]) for row in table) for column_index in range(len(table[0]))]
row_format = ["{:>"+str(width)+"}" for width in column_max_width]
for row in table:
    print("|".join([print_format.format(value) for print_format, value in zip(row_format, row)]))

输出:

number1| x|        name
     4x| 3|          Hi
      2| 1|808890312093
      5|Hi|         Bye

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为空间宽度,可根据需要进行调整。


尝试丰富: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


list1 = [1, 2, 3]
list2 = [10, 20, 30]

l = []

for i in range(0, len(list1)):
    l.append(list1[i]), l.append(list2[i])

# print(l)

for i in range(0, len(l), 2):
    print(l[i], "", l[i + 1])