在Python的列表列表中查找最长的列表 [英] Finding the longest list in a list of lists in Python
问题描述
我必须找出Python中最长的列表列表.
I have to fing the longest list of lists in Python.
例如:
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
也许递归会有所帮助? 谢谢!
Maybe recursion will help? Thank you!
推荐答案
以下是任何深度列表的递归解决方案:
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]
)
这篇关于在Python的列表列表中查找最长的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!