Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e. 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," "))
like image 607
Jean Zombie Avatar asked Feb 23 '16 14:02

Jean Zombie


1 Answers

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 :)

like image 196
Idos Avatar answered Sep 28 '22 18:09

Idos