将列表的输出格式化为列

2024-09-30 20:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个数据库,并试图列出该数据库中的所有表。我可以很好地打印它们,但我无法正确设置表格格式。我用熊猫来格式化它,这很有效,但我尝试在没有熊猫的情况下创建它。到目前为止,它是这样打印出来的:

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)

如何修复此错误?还是有其他方法可以做到这一点


Tags: in数据库forelementcursorlistrowheader
2条回答

可以使用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         

并非row中的每个元素都是字符串。不能使用intlen()。因此,在计算长度之前,请确保所有内容都是字符串

尝试进行以下更改:

以前

length_list = [len(element) for row in lst for element in row]

之后

length_list = [len(str(element)) for row in lst for element in row]

也可以更改这一行(将element换行为str()

以前

row = "".join(element.ljust(column_width + 2) for element in row)

之后

row = "".join(str(element).ljust(column_width + 2) for element in row)

相关问题 更多 >