python - 将列表列表中的输出格式化为列
问题描述
我正在使用一个数据库,我正在尝试列出该数据库中的所有表。我可以很好地打印它们,但我无法正确格式化表格。我使用 pandas 对其进行格式化并且可以正常工作,但我正在尝试在没有 pandas 的情况下创建它。到目前为止,它是这样打印出来的:
TerritoryID TerritoryDescription RegionID
1581 Westboro 1
1730 Bedford 1
1833 Georgetown 1
2116 Boston 1
2139 Cambridge 1
我试图让它看起来像这样:
TerritoryID TerritoryDescription RegionID
1. 1581 Westboro 1
2. 1730 Bedford 1
3. 1833 Georgetown 1
4. 2116 Boston 1
5. 2139 Cambridge 1
我尝试的是找到列表的最大长度并以这种方式格式化它们,因为我正在尝试格式化其他表。这是我尝试做的,但是,我得到一个错误,上面写着:object of type 'int' has no len()
def categories(menu, choice, cursor, connection):
sql = "SELECT * FROM " + menu[choice - 1]
cursor.execute(sql)
rows = cursor.fetchall()
lst = [list(elem) for elem in rows]
connection.close()
return lst
def columns(lst, cursor):
header = []
for field in cursor.description:
header.append(field[0])
print(' '.join(header))
length_list = [len(element) for row in lst for element in row]
column_width = max(length_list)
for row in lst:
row = "".join(element.ljust(column_width + 2) for element in row)
print(row)
我将如何解决此错误?还是有其他方法可以做到这一点?
解决方案
您可以使用 python 格式字符串将列表列表打印为表格:
# Input is expected as a list of list
rows = [
["TerritoryID", "TerritoryDescription", "RegionID"],
["1581", "Westboro", "1"],
["1730","Bedford","1"],
["1833","Georgetown","1"],
["2116","Boston","1"],
["2139","Cambridge","1"],
]
# First we get the max width of each column, like so:
max_col = list(max(map(len, x)) + 2 for x in list(map(list, zip(*rows))))
# Set some padding for the index column:
idx_pad = len(str(len(rows))) + 2
# Create a format string that will accept both values, and paddings:
s = "{:<{}}" + "{:<{}}" * len(max_col)
# Iterate the list of lists, printing each row:
for i, row in enumerate(rows):
if i == 0:
i = ""
c = row + max_col
c[::2] = row
c[1::2] = max_col
print(s.format(i, idx_pad, *c))
idx_pad = old_idx
这将打印出:
TerritoryID TerritoryDescription RegionID
1 1581 Westboro 1
2 1730 Bedford 1
3 1833 Georgetown 1
4 2116 Boston 1
5 2139 Cambridge 1
推荐阅读
- android - Lint 检查“RemoveWorkManagerInitializer”失败,如何解决?
- css - readall 未在 julia lang 中定义
- c++ - 全屏和放大 Koolplot
- flutter - 无法使用 ThemeData 为 AppBar 中的文本和 Scaffold 中的文本设置不同的颜色
- r - 有没有人能弄清楚为什么我的地图功能中的弹出窗口在 R 中点击时没有出现在地图上?使用传单
- django - 如何在 Django 中删除模型项并添加新项?
- hadoop - 删除 Hive 表和 msck 修复失败,表存储在谷歌云存储桶中
- css - 具有缩小图像的单列 flex 容器
- scala - 如何从 JsObject 中删除 Seq[String]?
- c++ - 如何在给定文件路径的情况下获取具有文件扩展名的文件名并将其存储在 C++ 控制台应用程序中的字符串中?