Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm attempting to define a function that takes a list of arrangements of strings and shows it in an efficient table with every section right-justified. Accept that all the inward lists will contain similar number of strings. For instance, the value could resemble this:

tableData = [['apples', 'oranges', 'cherries', 'banana'],

['Alice', 'Bob', 'Carol', 'David'],

['dogs', 'cats', 'moose', 'goose']]

What your function will print:

    apples Alice   dogs

   oranges   Bob   cats

  cherries Carol  moose

    banana David  goose

With a help of a hint, I came till here,

def printable(tableData):

    newTable = np.zeros((len(tableData[0]),len(tableData)))

    colWidths = [0] * len(tableData)

    for i in range(0,len(tableData)):

        colWidths[i] = max(tableData[i], key=len)

    largest = max(colWidths, key=len)

    for i in range(0,len(tableData)):

        for j in range(0,len(tableData[0])):

            newTable[i][j] = tableData[j][i].rjust(len(largest))

I'm horrified at the no. of for loops. As an amateur, I'm actually escaping the 'for-loop' mode. Likewise, I'm considering on the best type of assault for this issue. Much appreciated.

1 Answer

0 votes
by (26.4k points)

Here's single direction to do this in plain Python. We can use zip to transpose the table so we can get the most extreme width of every column.

table_data = [

    ['apples', 'oranges', 'cherries', 'banana'],

    ['Alice', 'Bob', 'Carol', 'David'],

    ['dogs', 'cats', 'moose', 'goose'],

]

# Determine the width of each column

widths = [max(map(len, column)) for column in zip(*table_data)]

new_table = [[s.rjust(w) for s, w in zip(row, widths)]

    for row in table_data]

for row in new_table:

    print(row)

output:

['apples', 'oranges', 'cherries', 'banana']

[' Alice', '    Bob', '   Carol', ' David']

['  dogs', '   cats', '   moose', ' goose']

In the event that you don't actually require another 2D list, and you simply need to print the data, you can accomplish something like this:

for row in table_data:

    print(*(s.rjust(w) for s, w in zip(row, widths)))

output:

apples oranges cherries banana

 Alice     Bob    Carol  David

  dogs    cats    moose  goose

Look at this new version which will transpose the table

widths = [max(map(len, row)) for row in table_data]

new_table = [[s.rjust(w) for s, w in zip(row, widths)] for row in zip(*table_data)]

for row in new_table:

    print(row)

output:

['  apples', 'Alice', ' dogs']

[' oranges', '  Bob', ' cats']

['cherries', 'Carol', 'moose']

['  banana', 'David', 'goose']

Interested to learn python in detail? Come and Join the python course.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 19, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...