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

问题描述 投票:2回答:7

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

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

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

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

对不起,这是一个非常简单的问题,但我不知所措。

在此先感谢您的帮助。

python python-3.x string-length
7个回答
6
投票

如你所知,len(tableData)给出了tableData元素的数量。你想要的是tableData元素元素长度的最大值:

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

>>> print(l)
8

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)

OUTPUT:

8

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


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

为这个答案贡献我的一份力量。


1
投票

你可以尝试循环...

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

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

print(maxLength)

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
© www.soinside.com 2019 - 2024. All rights reserved.