0

I am learning python and have been presented with the following practice problem. I am trying to take the following list and print it in a right-justified table.

tableData= [['apples', 'oranges', 'cherries' , 'banana'],
            ['Alice' , 'Bob' , 'Carol', 'David'],
            ['dogs' , 'cats' , 'moose', 'goose']]

And the output should look like this.

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

Here is my code.

tableData= [['apples', 'oranges', 'cherries' , 'banana'],
            ['Alice' , 'Bob' , 'Carol', 'David'],
            ['dogs' , 'cats' , 'moose', 'goose']]

def printTable(lists):
    colWidths = [0] * len(lists)
    for x in range(0, len(lists[0])):
        for y in range(0, len(lists)):
            colWidths[y] = len(max(lists[y]))
            fillChar= 0
            fillChar = colWidths[x] - len(lists[y][x])
            print(lists[y][x].rjust(fillChar, ' ' ) + ' ' , end = '' )

print(colWidths)
printTable(tableData)

The output I keep getting is below.

apples Alice dogs 
oranges Bob cats 
cherries Carol moose
 Traceback (most recent call last):
  File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 36, in <module>
    printTable(tableData)
  File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 17, in printTable
    fillChar = colWidths[x] - len(lists[y][x])
IndexError: list index out of range

Thanks for all your help

DakotaDickey44
  • 75
  • 1
  • 2
  • 7

3 Answers3

1

This is straightforward:

for item1, item2, item3 in zip(*tableData):
    print(item1.rjust(10) +  item2.rjust(10) + item3.rjust(10))

That will take care of getting your items for you individually and formatting it into a table. Your entire program has been condensed to two lines :)

This is how it works:

  • zip(l1,l2) takes two lists l1 and l2 and returns a single list with the corresponding elements of l1 and l2 merged into a tuple.
  • zip(*tableData) goes one step further and unpacks tableData into its individual lists. It's equivalent to doing zip(tableData[0], tableData[1], tableData[2]) in this case.
  • rjust(width) right justifies strings by width.
Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
  • while this works for the given list I need this to work regardless of the number of lists inside the larger list and the length of those inner lists. – DakotaDickey44 Apr 02 '16 at 04:07
  • This will work regardless of the number of lists inside the larger list. If you want it to work independent of the lengths of the inner lists, why not just append empty strings to inner lists until they are all the same length and then run this function? – Akshat Mahajan Apr 02 '16 at 04:09
  • See [this question](http://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length) for how to take care of inner lists with differing lengths using `zip`. – Akshat Mahajan Apr 02 '16 at 04:13
0

Just to follow up on the previous answer, this is a little more general ...

# Find the maximum length of the words ...
w = max([ max(map(len, m)) for m in tableData ]) + 1

# print the data ...
print '\n'.join([''.join(map(lambda x: str(x).rjust(w), m)) for m in zip(*tableData)])
ssm
  • 5,277
  • 1
  • 24
  • 42
0
list = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],         
        ['dogs', 'cats', 'moose', 'goose']]         


def swaplist(list):                                 
    result_list = []                                
    for index in range(0, len(list[0])):               
        temp_list = []                              
        for i in list:                              
            temp_list.append(i[index])              
        result_list.append(temp_list)               
    return result_list                              

print swaplist(list)                           

it is just print

list = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],         
        ['dogs', 'cats', 'moose', 'goose']]         


def swaplist(list):                                 
    for index in range(0, len(list[0])):               
        temp_list = []                              
        for i in list:                              
            temp_list.append(i[index])              
        print " ".join(temp_list)                   

swaplist(list)                                           
flatcoke
  • 82
  • 1
  • 8
  • This helps a lot. How would you go about printing with the rjust() method to ensure that the items are right justified the same amout? – DakotaDickey44 Apr 02 '16 at 04:22