计算嵌套列表的深度或最深级别
A 在作业上遇到了真正的问题(并且令人头疼)...
我正在上入门编程课程,我必须编写一个函数,给定一个列表,该函数将返回它所达到的“最大”深度.. 。 例如: [1,2,3] 将返回 1,[1,[2,3]] 将返回 2...
我已经编写了这段代码(这是我能得到的最好的 T_T)
def flat(l):
count=0
for item in l:
if isinstance(item,list):
count+= flat(item)
return count+1
但是,显然不能像它应该的那样工作,因为如果有不计入最大深度的列表,它仍然会提高计数器...
例如:当我使用带有 [1,2,[3,4] 的函数时, 5,[6],7] 它应该返回2,但它返回 3...
任何想法或帮助将不胜感激 ^^ 非常感谢!我已经为此苦苦挣扎了好几个星期了......
A have a real problem (and a headache) with an assignment...
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...
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...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
这是编写函数的一种方法
,我认为您缺少的想法是使用
max()
Here is one way to write the function
I think the idea you are missing is to use
max()
让我们首先稍微重新表述一下您的要求。
现在,这可以直接转换为代码:
Let's first rephrase your requirements slightly.
Now, this can be translated directly to code:
简单的递归
easy with recursion
广度优先,无需递归,它也适用于其他序列类型:
相同的想法,但内存消耗少得多:
Breadth-first, without recursion, and it also works with other sequence types:
The same idea, but with much less memory consumption:
用Python的一行代码完成的:)
享受
Did it in one line of python :)
enjoy
一种不需要任何额外模块并且无论深度如何都具有相同速度的方法:
基本上,它的作用是使用
repr()
将列表转换为字符串。然后,对于该字符串中等于“(
”或“[
”的每个字符,它会增加变量count
。对于右括号,它会减少<然后返回count
已达到的最大值。A way that does not need any additional modules and has the same speed, no matter what depth:
Basically, what this does is convert the list to a string using
repr()
. Then for every character in this string equal to "(
" or "[
" it increases the variablecount
. for the closing brackets it decreasescount
. It then returns the maximum thatcount
has reached.辱骂方式:
假设您的列表名为
mylist
这会将您的列表转换为左括号和右括号列表,然后查找在相应右括号出现之前出现的最大数量的左括号。
Abusive way:
Say your list is called
mylist
This converts your list to a list of opening and closing brackets, then finds the largest number of opening brackets that occur before the corresponding closing bracket occurs.
让我们坚持使用原始的、相当优雅的解决方案,并使用 max。许多其他解决方案都使用 lambda 表达式或需要外部库。这个使用“纯”Python 并保持简单。
奖励:此解决方案对空列表进行计数,并避免了遍历字符串的陷阱(假设您想对空列表进行计数)。
Let's stick with the original, fairly elegant solution and get it working using max. So many of the other solutions use lambda expressions or require external libraries. This one uses 'pure' python and keeps it simple.
Bonus: this solution counts empty lists and avoids the trap of traversing a string (provided you want to count empty lists).
在Numpy中,您可以将数据结构转换为
numpy数组
并使用其库函数。arr.shape
给出每层的长度,因此我们可以len()
形状并获取结构的深度:形状的 Numpy 文档:https://docs.scipy.org/doc/numpy/reference/ generated/numpy .ndarray.shape.html
In Numpy, you can convert the data structure to a
numpy array
and use its library functions.arr.shape
gives length per layer, so we canlen()
the shape and get the depth of the structure:Numpy docs for shape: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html
我为每个可迭代对象扩展了 hammar 的答案(默认情况下禁用字符串):
I extended the hammar's answer for every iterable (strings disabled by default):
如果您正在寻找快速修复方法
If you're looking for a quick fix
对上述内容进行简短补充,以便它也可以处理空列表:
A short addition to what has been said so it can handle empty lists too:
您也可以仅使用 python 递归地执行此操作:
这个函数是递归的,它的作用是它只是进入列表的最大深度,计算列表的深度,当它爬回来时,它只保留最大的深度在所有嵌套列表中注册。
you can also do it recursively using only python :
this function is recursive and what it does is that it just goes to the maximum depth of your list counting how deep the list is, and when it climbs back up, it keeps only the biggest deepness registered among all nested lists.
@John 的解决方案非常好,但是要解决空列表情况,例如
[]
、[[]]
或进一步嵌套的列表,您可能需要执行类似的操作@John's solution is excellent, but to address the empty list cases, like
[]
,[[]]
, or further nested lists, you may need to do something like this