如何在列表中查找嵌套列表的数量?

Oli*_*ver 16 python recursion list python-3.x

该函数接受一个列表并返回一个int,具体取决于列表中有多少列表不包括列表本身.(为简单起见,我们可以假设所有内容都是整数或列表.)

例如:

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

count_list(x) # would return 8
Run Code Online (Sandbox Code Playgroud)

我认为使用递归会有所帮助,但我不知道如何实现它,这是我到目前为止所做的.

def count_list(a,count=None, i=None):

    if count==None and i==None:
        count=0
        i=0
    if i>len(a)
        return(count)
    if a[i]==list
       i+=1
       count+=1
       return(count_list(a[i][i],count))
    else:
        i+=1
        return(count_list(a[i]))
Run Code Online (Sandbox Code Playgroud)

Kas*_*mvd 21

您可以使用递归函数执行此操作:

def count(l):
    return sum(1+count(i) for i in l if isinstance(i,list))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
>>> count(x)
8
Run Code Online (Sandbox Code Playgroud)

  • +1为"pythonic"方式来解决这个问题 (2认同)

lve*_*lla 17

这似乎做了这个工作:

def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count
Run Code Online (Sandbox Code Playgroud)

  • 好吧,从不了解Python的人的角度来看,我认为你的更具可读性,尽管他们显然做同样的事情.对于新手程序员来说,可读性在我看来胜过一两行;) (3认同)

Hai*_* Vu 5

这是一个非递归的解决方案:

  1. 首先,将列表中的每个项目放入堆栈
  2. 继续从堆栈中弹出一个项目,直到它耗尽为止
  3. 如果项目是一个列表:a)计算它,b)将每个项目推入堆栈

代码:

def count_list(lst):
    """ Given a master list, count the number of sub-lists """
    stack = lst[:]
    count = 0
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            # If the item is a list, count it, and push back into the
            # stack so we can process it later
            count += 1
            stack.extend(item)
    return count
Run Code Online (Sandbox Code Playgroud)