在Python中查找列表列表中最长的列表

2024-04-29 02:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须在Python中查找最长的列表列表。

例如:

longest([1,2,3])返回3

longest([[[1,2,3]]])还返回3(内部列表为3)

longest([[], [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]], [1,2,3,4,5]])返回7(list[3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]]包含7个元素)

现在我有了这段代码,但它并不能解决前两个示例的问题。。

def longest(list1):
    longest_list = max(len(elem) for elem in list1)
    return longest_list

也许递归会有帮助? 谢谢您!


Tags: 代码in元素示例列表forlenreturn
3条回答

Python3.3版本:

def lengths(x):
    if isinstance(x,list):
        yield len(x)
        for y in x:
            yield from lengths(y)

用法:

>>> l = [[], [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]], [1,2,3,4,5]]
>>> max(lengths(l))
7

在Python2.6+中,没有yield from语句(在Python3.3中引入),因此必须稍微更改代码:

def lengths(x):
    if isinstance(x,list):
        yield len(x)
        for y in x:
            for z in lengths(y):
                yield z

这几行对我来说很简单,我的列表是嵌套的(列表列表)

#define the function#
def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

#print output#
find_max_list(your_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]))

相关问题 更多 >