I'm working through Automate the Boring Stuff with Python and have found a project I can seem to crack. It's pretty printing a lists of lists so they are all right justified, so you have to find the longest string length in the given lists of lists. I have tried to concat the lists of list together into one list, then find the max
len
value from that, and sub that into a for loop to print every string justified to that length, but it doesnt seem to be working. My code isn't taking the max length of all of the string values. I think it's only taking the max length from the first list because it says the max length is 7 (from 'oranges'
i assume), when it should be 8 (from 'cherries'
). My only guess is that is has something to do with itertools, and that itertools.chain doesnt instantly concat the list of lists in one action, but instead iterates through them as a list, so the first iteration took the first list, and longWord
function took the max of only that first list instead of the entire concated new list. Any idea how I can fix this code to make it work properly?
Also, is there an easier way to concat lists, for example in Haskell, there is just a concat
function to concat any given set of list of lists. Is there anything shorter than the itertools.chain.from_iterable
thing?
import itertools
def printTable(table):
newlist = list(itertools.chain.from_iterable(tableData))
longWord = len(max(newlist))
for i in range(len(table[0])):
for j in range(len(table)):
print ((table[j][i]).rjust(longWord), end = " ")
print ("\n")
print (newlist)
print (str(longWord))
print (max(newlist))
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]