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
这篇关于计算嵌套列表的深度或最深级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算嵌套列表的深度或最深级别


- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01