dhc*_*ona 22 python nested list levels
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 ...
任何想法或帮助将非常感谢^^非常感谢!! 我已经持续数星期了......
Joh*_*ooy 27
这是编写函数的一种方法
depth = lambda L: isinstance(L, list) and max(map(depth, L))+1
我认为你缺少的想法是使用 max()
ham*_*mar 12
让我们首先略微重述您的要求.
列表的深度比其子列表的最大深度多一个.
现在,这可以直接转换为代码:
def depth(l):
    if isinstance(l, list):
        return 1 + max(depth(item) for item in l)
    else:
        return 0
递归很容易
def flat(l):
    depths = []
    for item in l:
        if isinstance(item, list):
            depths.append(flat(item))
    if len(depths) > 0:
        return 1 + max(depths)
    return 1
广度优先,没有递归,它也适用于其他序列类型:
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)))
同样的想法,但内存消耗更少:
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
| 归档时间: | 
 | 
| 查看次数: | 16957 次 | 
| 最近记录: |