I tried to find the answer but most of the answers use advance functions like map() or zip(). I have to use only string attributes, methods or functions. I could not find answer with string functions or attributes.
I need to print a given lists of list into a right justified columns. Its a kind of transpose of each sub list i.e. the first list in the lists of list is printed as fist column of the table, the second list second column and so on.
The given lists of lists:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
and the desired output:
Note that the argument to rjust() comes from the max length of the longest word in the tableData.
I have figured out the max integer length of the longest word in tableData as follows:
colWidths=[]
for i in range(len(tableData)):
maxL=len(max(tableData[i], key=len))
colWidths.append(maxL)
max(colWidths)
Now I am stuck how to write a loop to print the lists in required table format. (I could do it using zip() or map() but thats not accepted!) Any help?
If you don't want to transpose table, you can do it dirty way:
for column in range(4):
for row in range(3):
print(tableData[row][column].rjust(10), end='')
print('')
Column/row range can be set dynamically, if your task needs it