计算嵌套列表的深度或最深级别

Counting depth or the deepest level a nested list goes to(计算嵌套列表的深度或最深级别)

本文介绍了计算嵌套列表的深度或最深级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A 有一个真正的问题(而且很头疼)做作业...

A have a real problem (and a headache) with an assignment...

我正在上一门介绍性编程课程,我必须编写一个函数,在给定列表的情况下,该函数将返回它达到的最大"深度...例如:[1,2,3] 将返回 1,[1,[2,3]] 将返回 2...

I'm in an introductory programming class, and I have to write a function that, given a list, will return the "maximum" depth it goes to... For example: [1,2,3] will return 1, [1,[2,3]] will return 2...

我写了这段代码(这是我能得到的最好的T_T)

I've written this piece of code (it's the best I could get T_T)

def flat(l):
    count=0
    for item in l:
        if isinstance(item,list):
            count+= flat(item)
    return count+1

然而,它显然不像它应该的那样工作,因为如果有不计入最大深度的列表,它仍然会增加计数器......

However, It obviously doens't work like it should, because if there are lists that do not count for the maximum deepness, it still raises the counter...

例如:当我使用带有 [1,2,[3,4],5,[6],7] 的函数时,它应该返回 2,但它返回 3...

For example: when I use the function with [1,2,[3,4],5,[6],7] it should return 2, but it returns 3...

任何想法或帮助将不胜感激^^ 非常感谢!!我已经为此苦苦挣扎了几个星期...

Any ideas or help would be greatly appreciated ^^ thanks a lot!! I've been strugling with this for weeks now...

推荐答案

广度优先,没有递归,也适用于其他序列类型:

Breadth-first, without recursion, and it also works with other sequence types:

from collections import Sequence
from itertools import chain, count

def depth(seq):
    for level in count():
        if not seq:
            return level
        seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence)))

相同的想法,但内存消耗要少得多:

The same idea, but with much less memory consumption:

from collections import Sequence
from itertools import chain, count

def depth(seq):
    seq = iter(seq)
    try:
        for level in count():
            seq = chain([next(seq)], seq)
            seq = chain.from_iterable(s for s in seq if isinstance(s, Sequence))
    except StopIteration:
        return level

这篇关于计算嵌套列表的深度或最深级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:计算嵌套列表的深度或最深级别

基础教程推荐