首页 > 解决方案 > 将列表列表中的输出格式化为列

问题描述

我正在使用一个数据库,我正在尝试列出该数据库中的所有表。我可以很好地打印它们,但我无法正确格式化表格。我使用 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)

我将如何解决此错误?还是有其他方法可以做到这一点?

标签: pythondatabaselistsqlite

解决方案


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

推荐阅读