简体   繁体   English

如何在嵌套列表中获取最大字符串长度

[英]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这给了我 7、5、5。但是“樱桃”是 8

what a my missing here?我在这里想念什么? Thanks.谢谢。

You've done the length of the maximum word .你已经完成了最大 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.在字符串操作中max将从字符串中返回最大的字母字符,而不是长度的基础。 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. sum(tableData,[])将转换成list of list ,以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). Python 计算max字符串元素作为字典中最后出现的元素(字典排序)。 What you want instead is max(len(s) for s in i) instead of len(max(i))你想要的是max(len(s) for s in i)而不是len(max(i))

for row in tableData:
    print(max(len(s) for s in row))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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