0

The goal of this program was to take in a nested list called tableData and write a function that displays organized columns that are right-justified. The function works for the code but I would like to get some feedback or to know if I can be done more efficiently for problems in the future.

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

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

def printTable():
    colWidths = [0]* len(tableData)
    one = []
    two = []
    three = []


    for i in range(len(tableData)):
        colWidths[i] = tableData[i]
        place = tableData[i]
        for x in range(len(tableData[i])):
            spot = colWidths
            if len(one) < len(place):
                one.append(colWidths[i][x])
            elif len(two) < len(place):
                two.append(colWidths[i][x])
            elif len(three) < len(place):
                three.append(colWidths[i][x])

    for i in range(len(one)):
        print((one[i]+'  ' +two[i]+ '  ' +three[i]).center(20,))


printTable() 
2
  • 1
    You may want to try over at CodeReview (codereview.stackexchange.com), which is a great spot for getting tips on improving working code. Commented Apr 13, 2020 at 4:27
  • In case you're looking for a ready-made solution, I've had success using the tabulate module (github.com/astanin/python-tabulate). It's included in Anaconda, and available in the Debian repositories if you don't want to use pip. Commented Apr 13, 2020 at 5:04

3 Answers 3

3

Python has a built in method called zip which allows us to combine iterables into a single variable. If you were to combine this with pythons unpacking ability, the code becomes quite condensed.

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

things = list(zip(*tableData))
for tuple in things:
    print('{} {} {}'.format(*tuple).rjust(20))

What we did here was to take the tabledata and split it using the unpacker *, then we zip it, so we get a tuple containing one of each value from the separated lists.

We then iterate through things and split each tuple, again using unpacking. Finally, we can use rjust() to get that right justify

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of trying loop, you can try below -

import pandas as pd

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

df = pd.DataFrame(tableData)

df_transpose = df.transpose()


df_transpose['final'] = df_transpose.apply(lambda x: ' '.join(x.dropna().values.tolist()), axis=1)

with pd.option_context('display.colheader_justify','right'):
    print(df_transpose['final'].to_string(index=False,header=False))

Comments

0

Your answer not takes in all length of the strings in the list values. Also the length of the longest string should be given as width value for rjust.

AnswerCode:

tableData=[["apples","oranges","cherries","banana"],
           ["Alice","Bob","Carol","David"],
           ["dogs","cat","moose","goose"]]
colWidth=[0]*len(tableData)     
def printtable(data):
    colWidths = [0] * len(tableData)
    
    for y in range(len(tableData)): #finding the length of strings in each sublist
        for x in tableData[y]:
            if colWidths[y] < len(x):
                colWidths[y] = len(x)
    width=max(colWidths) # finding the length of the longest in the list
    for j in range(len(data[0])):     
        for i in range(len(data)):
            print(data[i][j].rjust(int(width)), end = " ")
        print("\n")
printtable(tableData)

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.