将列表打印为表格数据

本文翻译自:Printing Lists as Tabular Data

I am quite new to Python and I am now struggling with formatting my data nicely for printed output. 我是Python的新手,现在正努力为打印输出很好地格式化数据。

I have one list that is used for two headings, and a matrix that should be the contents of the table. 我有一个用于两个标题的列表,以及一个应该作为表内容的矩阵。 Like so: 像这样:

teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = np.array([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])

Note that the heading names are not necessarily the same lengths. 请注意,标题名称不一定是相同的长度。 The data entries are all integers, though. 数据条目都是整数。

Now, I want to represent this in a table format, something like this: 现在,我想以表格格式表示此内容,如下所示:

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

I have a hunch that there must be a data structure for this, but I cannot find it. 我有一个预感,为此必须有一个数据结构,但是我找不到它。 I have tried using a dictionary and formatting the printing, I have tried for-loops with indentation and I have tried printing as strings. 我尝试使用字典并格式化打印,尝试使用缩进进行for循环,并尝试将打印为字符串。

I am sure there must be a very simple way to do this, but I am probably missing it due to lack of experience. 我确信必须有一种非常简单的方法来执行此操作,但是由于缺乏经验,我可能会错过它。


#1楼

参考:https://stackoom.com/question/e0ji/将列表打印为表格数据


#2楼

Python actually makes this quite easy. Python实际上使这变得非常容易。

Something like 就像是

for i in range(10):
    print '%-12i%-12i' % (10 ** i, 20 ** i)

will have the output 将有输出

1           1           
10          20          
100         400         
1000        8000        
10000       160000      
100000      3200000     
1000000     64000000    
10000000    1280000000  
100000000   25600000000
1000000000  512000000000

The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. 字符串中的%本质上是一个转义字符,其后的字符告诉python数据应采用哪种格式。 The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified. 字符串前后的%告诉python您打算将前一个字符串用作格式字符串,并将以下数据放入指定的格式中。

In this case I used "%-12i" twice. 在这种情况下,我两次使用了“%-12i”。 To break down each part: 分解每个部分:

'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)

From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting 从文档中: https : //docs.python.org/2/library/stdtypes.html#string-formatting


#3楼

There are some light and useful python packages for this purpose: 有一些轻巧实用的python软件包可用于此目的:

1. tabulate : https://pypi.python.org/pypi/tabulate 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 has many options to specify headers and table format. 制表具有许多选项来指定标题和表格式。

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 2. PrettyTablehttps//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 has options to read data from csv, html, sql database. PrettyTable具有从csv,html,sql数据库读取数据的选项。 Also you are able to select subset of data, sort table and change table styles. 您还可以选择数据子集,对表进行排序和更改表样式。

3. texttable : https://pypi.python.org/pypi/texttable 3. texttablehttps : //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  |
+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types. 使用texttable,您可以控制水平/垂直对齐,边框样式和数据类型。

4. termtables : https://github.com/nschloe/termtables 4. termtableshttps : //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  |
+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types. 使用texttable,您可以控制水平/垂直对齐,边框样式和数据类型。

Other options: 其他选项:

  • terminaltables Easily draw tables in terminal/console applications from a list of lists of strings. terminaltables从字符串列表中轻松在终端/控制台应用程序中绘制表。 Supports multi-line rows. 支持多行。
  • asciitable Asciitable can read and write a wide range of ASCII table formats via built-in Extension Reader Classes. asciitable Asciitable可以通过内置的扩展阅读器类读取和写入各种ASCII表格式。

#4楼

Updating Sven Marnach's answer to work in Python 3.4: 更新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))

#5楼

When I do this, I like to have some control over the details of how the table is formatted. 当我这样做时,我希望对表格的格式化细节有一些控制。 In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. 特别是,我希望标头单元格具有与主体单元格不同的格式,并且表列的宽度仅应满足每个单元格所需的宽度。 Here's my solution: 这是我的解决方案:

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', ' | ')

Here's the output: 这是输出:

                   | 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

#6楼

Pure Python 3 纯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)

Will print 将打印

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值