[Python] Print a list of lists as a table in Python

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    I've a list,

    L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
    ['Jane', 'Doe', '3.5', 'CS', '2'], ['Joe', 'Doe', '2.0', 'CpE', '0'],
    ['Todd', 'Brown', '3.88', 'CS', '5'],
    ['Mike', 'Smith', '3.88', 'CS', '5']]


    And I've to print it in a table like:

    --------------------------------------------------------
    | First| Last| GPA| Major| Drops|
    --------------------------------------------------------
    | Jane| Doe| 3.50| CS| 2|
    | Joe| Doe| 2.00| CpE| 0|
    | Todd| Brown| 3.88| CS| 5|
    | Mike| Smith| 3.88| CS| 5|


    My code is so far:

    L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
    ['Jane', 'Doe', '3.5', 'CS', '2'],
    ['Joe', 'Doe', '2.0', 'CpE', '0'],
    ['Todd', 'Brown', '3.88', 'CS', '5'],
    ['Mike', 'Smith', '3.88', 'CS', '5']]
    count1 = 1
    while count1 < len(L):
    L[count1][2] = float(L[count1][2])
    L[count1][4] = int(L[count1][4])
    count1 += 1
    h_line = 56 * '-'
    first_line = "|"
    print (h_line)
    s = " "
    w = 10
    for i in range(len(L[0])):
    str1 = (s*(w - len(L[0])) + "%s|" % L[0])
    first_line = first_line + str1
    print(first_line)
    print(h_line)
    a = 1
    while a < len(L):
    second_line = "|"
    for j in range (len(L[a])):
    if type(L[a][j]) == str :
    str2 = (s*(w - len(L[a][j])) + ("%s|" % L[a][j]))
    second_line = second_line + str2
    elif type(L[a][j]) == float :
    str2 = (s*(w-4) + ("%.2f|" % L[a][j]))
    second_line = second_line + str2
    elif type(L[a][j]) == float :
    str2 = (s*(w-1) + ("%i|" % L[a][j]))
    second_line = second_line + str2
    print (second_line)
    a = a + 1


    print (h_line)


    But my output looks like:

    --------------------------------------------------------
    | First| Last| GPA| Major| Drops|
    --------------------------------------------------------
    | Jane| Doe| 3.50| CS|
    | Joe| Doe| 2.00| CpE|
    | Todd| Brown| 3.88| CS|
    | Mike| Smith| 3.88| CS|
    --------------------------------------------------------


    I can't figure out what I'm doing wrong.

    Continue reading...

Compartilhe esta Página