我正在使用一个数据库,并试图列出该数据库中的所有表。我可以很好地打印它们,但我无法正确设置表格格式。我用熊猫来格式化它,这很有效,但我尝试在没有熊猫的情况下创建它。到目前为止,它是这样打印出来的:
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格式字符串将列表列表打印为表格:
将打印出:
并非
row
中的每个元素都是字符串。不能使用int
的len()
。因此,在计算长度之前,请确保所有内容都是字符串尝试进行以下更改:
以前
之后
也可以更改这一行(将
element
换行为str()
:以前
之后
相关问题 更多 >
编程相关推荐