Python 将列表打印为表格数据

Python 将列表打印为表格数据,python,Python,我是Python新手,现在正努力将数据格式化为打印输出 我有一个用于两个标题的列表和一个矩阵,它应该是表的内容。像这样: teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0], [2, 4, 2]]) 请注意,标题名称的长度不一定相同。不过,数据项都是整数 现在,我想用一种表格格式来表示它,类似这样: &g

我是Python新手,现在正努力将数据格式化为打印输出

我有一个用于两个标题的列表和一个矩阵,它应该是表的内容。像这样:

teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = np.array([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])
请注意,标题名称的长度不一定相同。不过,数据项都是整数

现在,我想用一种表格格式来表示它,类似这样:

>>> print_table(table)

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2
曼城Utd曼城T温泉酒店
曼联1 0 0
曼城110
T温泉0 1 2
我有一种预感,这一定有一个数据结构,但我找不到它。我尝试过使用字典和格式化打印,我尝试过缩进循环和字符串打印

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

我想这就是你想要的

这是一个简单的模块,只需计算表项所需的最大宽度,然后使用and对数据进行漂亮的打印

如果您希望左标题向右对齐,只需更改此呼叫:

 print >> out, row[0].ljust(col_paddings[0] + 1),
从第53行开始,带:

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

我会尝试循环浏览列表,并使用CSV格式化程序来表示所需的数据

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

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

一些特殊代码:

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实际上使这变得非常容易

差不多

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)

从文档中:

有一些用于此目的的轻量级实用python包:

1。制表

从表格导入表格
打印(表格(['Alice',24],'Bob',19]],标题=['Name','Age']))
tablate有许多选项来指定标题和表格格式

print(制表(['Alice',24],'Bob',19]],标题=['Name','Age',tablefmt='orgtbl'))
2。漂亮的桌子

从prettytable导入prettytable
t=PrettyTable(['Name','Age']))
t、 添加_行(['Alice',24])
t、 添加行(['Bob',19])
打印(t)
PrettyTable具有从csv、html和sql数据库读取数据的选项。此外,您还可以选择数据子集、对表格进行排序和更改表格样式

3。text表格

从texttable导入texttable
t=文本表()
t、 添加_行(['Name','Age',['Alice',24','Bob',19]])
打印(t.draw())
使用texttable,您可以控制水平/垂直对齐、边框样式和数据类型

4。术语表

将术语表导入为tt
字符串=tt.to_字符串(
[[“爱丽丝”,24],“鲍勃”,19],
页眉=[“姓名”,“年龄”],
style=tt.styles.ascii\u thin\u double,
#alignment=“ll”,
#填充=(0,1),
)
打印(字符串)
使用texttable,您可以控制水平/垂直对齐、边框样式和数据类型

其他选择:

  • 从字符串列表轻松地在终端/控制台应用程序中绘制表格。支持多行
  • 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', ' | ')
纯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

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

注意:对于Python2中的直接等效项,您可以用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
”,将其替换为
“|”。join

参考资料:

  • 很多关于格式(旧格式和新格式) (款式)
  • 官方Python教程(相当不错)-
  • 官方Python信息(可能很难阅读)-
  • 另一种资源-

一种简单的方法是循环所有列,测量它们的宽度,为最大宽度创建一个行模板,然后打印行这不完全是您要寻找的,因为在这种情况下,您首先必须将标题放在表中,但我认为它可能对其他人有用

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

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

我知道我参加聚会迟到了,但我刚刚为此制作了一个库
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
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)
#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()
          Man Utd  Man City  T Hotspur
  Man Utd       1       2       1   
 Man City       0       1       0   
T Hotspur       2       4       2   
+--------------------------------------------+
| 4            | 3            | Hi           |
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+
+--------------------------------------------+
| 4            | 3            | Hi           |
+--------------+--------------+--------------+
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+
+-----------------------------------------------+
| Name                  | Email                 |
+-----------------------+-----------------------+
| Richard               | richard@fakeemail.com |
| Tasha                 | tash@fakeemail.com    |
+-----------------------------------------------+
+-----------------------+
|       | a     | b     |
+-------+-------+-------+
| x     | a + x | a + b |
| z     | a + z | z + b |
+-----------------------+
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)
Amplitude      :  1.438 m³/h
MAE            :  0.171 m³/h
MAPE           : 27.740 %
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