简体   繁体   中英

How to get a max string length in nested lists

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.

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))

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'

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM