Reputation: 107
They is a follow up question to my earlier post (re printing table from a list of lists)
I'm trying t get a string max value of the following nested list:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
for i in tableData:
print(len(max(i)))
which gives me 7, 5, 5. But "cherries" is 8
what a my missing here? Thanks.
Upvotes: 4
Views: 2748
Reputation: 16081
In string operations max
will Return the maximum alphabetical character from the string, not in basics of length. So you have to do something like this.
len(max(sum(tableData,[]),key=len))
sum(tableData,[])
will convert the list of list
to list
this helps to iterate through the list of list.
Length in each row
In [1]: [len(max(i,key=len)) for i in tableData]
Out[1]: [8, 5, 5]
See the difference,
In [2]: max(sum(tableData,[]))
Out[2]: 'oranges'
In [3]: max(sum(tableData,[]),key=len)
Out[3]: 'cherries'
Upvotes: 1
Reputation: 113905
You were printing the length of the max element in each row. Python computes the max
string element as the one that is seen last in a dictionary (lexicographic sorting). What you want instead is max(len(s) for s in i)
instead of len(max(i))
for row in tableData:
print(max(len(s) for s in row))
Upvotes: -1
Reputation: 362497
You've done the length of the maximum word. This gives the wrong answer because words are ordered lexicographically:
>>> 'oranges' > 'cherries'
True
What you probably wanted is the maximum of the lengths of words:
max(len(word) for word in i)
Or equivalently:
len(max(i, key=len))
Upvotes: 7