简体   繁体   中英

Print lists in a list in columns

I have a list with lists and I want to print it in columns w/o any additional modules to import (ie pprint ). The task is only for me to understand iteration over lists. This is my list of lists:

tableData = [['a', 'b', 'c', 'd'],
            ['1', '2', '3', '4'],
            ['one', 'two', 'three', 'four']]

And I want it to look like this:

a    1    one
b    2    two
c    3    three
d    4    four

I managed to somewhat hard-code the first line of it but I can't figure out how to model the iteration. See:

def printTable(table):
    print(table[0][0].rjust(4," ") + table[1][0].rjust(4," ") + table[2][0].rjust(4," "))

You can use zip() like so:

>>> for v in zip(*tableData):
        print (*v)

a 1 one
b 2 two
c 3 three
d 4 four

You can obviously improve the formatting (like @Holt did very well) but this is the basic way :)

You can use zip to transpose your table and then use a formatted string to output your rows:

row_format = '{:<4}' * len(tableData)
for t in zip(*tableData):
    print(row_format.format(*t))

You want to transpose this. This is most easy in python. After that, you just need to care about your own printing format.

transposed_tabe = zip(*tableData )

if you have a list as my_list = [('Math', 80), ('Physics',90), ('Biology', 50)] then we can say this is 3X2 matrix. The transpose of it will 2X3 matrix.

transposed_tabe = zip(*my_list )

will make following output

[('Math', 'Physics', 'Biology'), (80, 90, 50)]

If you still want mutable strings, simply print one row at a time:

for k in range(len(tableData[0])):
    for v in range(len(tableData)):
        print(tableData[v][k], end = ' ')
    print()

In this way you can use classic string methods ljust() rjust() and center() to format your columns.

If you want to automate use of .rjust, assuming you have lists with same number of strings, you can do it like this:

def printTable(data):
    colWidths = [0] * len(data)
    for i in range(len(data)):
        colWidths[i] = len(max(data[i], key=len))

    for item in range(len(data[0])):
        for i in range(len(data)):
            print(str(data[i][item]).rjust(colWidths[i]), end=' ')
        print()


printTable(tableData)

This way you don't have to manually check the length of the longest string in list. Result:

a 1   one 
b 2   two 
c 3 three 
d 4  four 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM