计算嵌套列表进入的深度或最深层次

编程入门 行业动态 更新时间:2024-10-27 08:37:50
本文介绍了计算嵌套列表进入的深度或最深层次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个作业确实有一个问题(和令人头疼)...

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

更多推荐

计算嵌套列表进入的深度或最深层次

本文发布于:2023-10-30 07:51:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542236.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   最深   深度   层次   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!