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
这篇关于计算嵌套列表的深度或最深级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算嵌套列表的深度或最深级别
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01