Python Prettytable 分隔每个表
Posted
技术标签:
【中文标题】Python Prettytable 分隔每个表【英文标题】:Python Prettytable Separating Each Table 【发布时间】:2021-12-14 04:50:21 【问题描述】:我有一个小问题。如果它们具有相同的列名,我如何拆分表?
这是一个例子:
+----------------------------+
| AUDIO TRACKS |
+----+----------+------------+
| ID | LangCode | LangName |
+----+----------+------------+
| 1 | de | German |
| 2 | de | German |
| 3 | en | English |
| 4 | en | English |
| 5 | es | Spanish |
| 6 | es | Spanish |
+----------------------------+
这是我想要的输出
+----------------------------+
| AUDIO TRACKS |
+----+----------+------------+
| ID | LangCode | LangName |
+----+----------+------------+
| 1 | de | German |
| 2 | de | German |
|----------------------------|
| 3 | en | English |
| 4 | en | English |
|----------------------------|
| 5 | es | Spanish |
| 6 | es | Spanish |
+----------------------------+
【问题讨论】:
【参考方案1】:您可以使用 itertools.groupby
执行此操作,并在每个组之后添加 split_row,如下所示:
from prettytable import PrettyTable
from itertools import groupby
myTable = PrettyTable(["ID", "LongCode", "LangName"])
lst = [["1", "de", "German"], ["2", "de", "German"],
["3", "en", "English"], ["4", "en", "English"],
["5", "es", "Spanish"], ["4", "es", "Spanish"]]
split_row = ['—' * x for x in [2, 8, 10]]
myTable.title = 'AUDIO TRACKS'
for key, group in groupby(lst, lambda x: x[1]):
for g in group:
myTable.add_row(g)
myTable.add_row(split_row)
print(myTable)
输出:
+----------------------------+
| AUDIO TRACKS |
+----+----------+------------+
| ID | LongCode | LangName |
+----+----------+------------+
| 1 | de | German |
| 2 | de | German |
| —— | ———————— | —————————— |
| 3 | en | English |
| 4 | en | English |
| —— | ———————— | —————————— |
| 5 | es | Spanish |
| 4 | es | Spanish |
| —— | ———————— | —————————— |
+----+----------+------------+
【讨论】:
非常感谢 :) 这就是我要找的。我为 split_row 做了一点点,因为我有这么多列,就是乘以破折号 :) @mark12345 已编辑答案以上是关于Python Prettytable 分隔每个表的主要内容,如果未能解决你的问题,请参考以下文章
Python:将列附加到 PrettyTable 中的现有表
ImportError: No module named prettytable的处理方法