簡體   English   中英

如何獲取嵌套字符串列表中最長字符串的長度?

[英]How to get the length of the longest string in a nested list of strings?

這里是Python的新手。 我試圖在一系列嵌套列表中找到一個值的最長長度。 這是一個示例列表類型:

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

我想要的答案是8 ,但如果列表更新,這可能會改變。

當我使用print(len(tableData))我得到3,嵌套列表的數量。 我無法得到解決這個問題的循環工作。

對不起,這是一個非常簡單的問題,但我不知所措。

先謝謝您的幫助。

如您len(tableData)len(tableData)給出了tableData的元素數。 你想要的是tableData元素的元素長度的最大值:

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

>>> print(l)
8

迭代每個元素並獲取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
from itertools import chain

chain.from_iterable(tableData)

現在,這就好像您有一個長單列值列表,而不是值列表列表。 現在找到那個扁平化列表中最長的項目是微不足道的:

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

這將返回'cherries'

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

這返回8

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

為這個答案貢獻我的一份力量。

也許這對你有用:

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

你可以嘗試循環...

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

print(maxLength)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM