计算嵌套列表进入的深度或最深层次 [英] Counting depth or the deepest level a nested list goes to
问题描述
一个作业确实有一个问题(和令人头疼)...
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
这篇关于计算嵌套列表进入的深度或最深层次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!