[hacker bank] - Day 11: 2D Arrays --- table printing

Format and print the table of two-dimensional array.
For example: given a table (that is, the number of each list element in the list is the same, otherwise it can't be printed. There are 3 lists in total, and each list has 4 strings):
tableData = [
['apple', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
You want to format the output to right as follows:

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

The idea is:
1. First, you need to get the maximum value of the string in each sublist in the list, which is the parameter required for the right alignment method rjust
2. Then traverse the two-dimensional array for printing, and press enter after printing 3 col strings (note that it cannot be line feed), so that the final column is a right aligned sub list, which is the final effect

#! /usr/bin/python3

def printTable(data_list):
    # Define a list to store the length of the longest string of each sublist
    str_maxlen_list = [0]*len(data_list)
    # Traverse the two-dimensional array, get the length of the longest string of each sublist and co-exist it in str ﹣ maxlen ﹣ list
    for i in range(len(data_list)):
        for j in range(len(data_list[i])):
            if len(data_list[i][j]) >= str_maxlen_list[i]:
                str_maxlen_list[i] = len(data_list[i][j])
    # Traverse the two-dimensional array again (first traverse the inner list, then traverse the outer list -- because each column needs to be right aligned inner list for the final printing)
    for i in range(len(data_list[0])):
        for j in range(len(data_list)):
            # Note that when printing, only three col strings are wrapped (three col strings are connected with spaces or tabs and printed)
            print(data_list[j][i].rjust(str_maxlen_list[j]) + ' ', end='')
        # Carriage return \ r operation. If line feed is written here, the effect may not be good!
        print('\r')

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

printTable(tableData)

The effect is right alignment, as follows:

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

Posted by big_c147 on Wed, 01 Jan 2020 21:29:52 -0800