在不规则列表中查找最长列表的长度 [英] Finding length of the longest list in an irregular list of lists
本文介绍了在不规则列表中查找最长列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在列表列表中找到最长的列表.
I have to find the longest list inside a list of lists.
例如:
longest([1,2,3])
返回3
longest([[[[1,2,3]]])
也返回3(内部列表为3)
longest([[[1,2,3]]])
also returns 3 (inner list is 3)
longest([[],[3,[4,5],[2,3,4,5,3,3],[7],5,[1,2,3],[3,4]],[1,2,3,4,5]])
返回7(列表 [3,[4,5],[2,3,4,5,3,3],[7],5,[1,2,3],[3,4]]
包含7个元素)
longest([[], [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]], [1,2,3,4,5]])
returns 7 (list [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]]
contains 7 elements)
现在我有了这段代码,但是前两个示例并没有解决问题.
Right now I have this code, but it doesn't do the trick with the first two examples.
def longest(list1):
longest_list = max(len(elem) for elem in list1)
return longest_list
也许递归会有所帮助?
推荐答案
以下是任何深度列表的递归解决方案:
Here is a recursive solution for any depth list:
def longest(l):
if not isinstance(l, list):
return 0
return max(
[len(l)]
+ [len(subl) for subl in l if isinstance(subl, list)]
+ [longest(subl) for subl in l]
)
这篇关于在不规则列表中查找最长列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文