如何获取嵌套的字符串列表中最长的字符串的长度?

时间:2019-03-20 12:20:18

标签: python python-3.x string-length

Python的新手。我试图在一系列嵌套列表中找到一个值的最长长度。这是一个示例列表类型:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

我在这里想要的答案是8,但是如果列表被更新,这可能会改变。

使用print(len(tableData))时得到3,即嵌套列表的数量。我也无法解决这个问题。

很抱歉,这是一个非常简单的问题,但我很茫然。

预先感谢您的帮助。

7 个答案:

答案 0 :(得分:6)

您注意到,len(tableData)给出了tableData的元素数。您需要的是tableData中的元素 的最大长度:

l = max(len(x) for sublist in tableData for x in sublist)

>>> print(l)
8

答案 1 :(得分:4)

遍历每个元素并获取其len()进行比较。

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

maxCount = 0
for lst in tableData:
    for elem in lst:
        maxCount = max(maxCount, len(elem))

print(maxCount)

输出

8

答案 2 :(得分:3)

from itertools import chain

chain.from_iterable(tableData)

这现在的行为就好像您有一个长长的单值列表,而不是一列值列表。现在,在该扁平化列表中找到最长的项很简单:

max(chain.from_iterable(tableData), key=len)

这将返回'cherries'

max(map(len, chain.from_iterable(tableData)))

这将返回8

答案 3 :(得分:2)

>>> import numpy as np
>>> data=np.array([['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]).reshape(-1)
>>> max(data,key=len)
'cherries'
>>> len(max(data,key=len))
8

为这个答案贡献自己的力量。

答案 4 :(得分:1)

也许这对您有用:

new_list = []
for sub_list in tableData:
    for item in sub_list:
        new_list.append(item)

max_element = max(new_list, key=len)

print(max_element) # this actually prints the item
print(len(max_element)) # this will give you the length

答案 5 :(得分:1)

您可以尝试循环...

l = 0 
for row in tableData: 
     for col in row: 
         l = len(col) if l < len(col) else l 

答案 6 :(得分:1)

maxLength = 0
for row in tableData:
    maxRowElementLength = len(max(row, key=len))
    if maxLength < maxRowElementLength:
        maxLength = maxRowElementLength

print(maxLength)