如何在列表中查找嵌套列表的数量? [英] How to find the number of nested lists in a list?

查看:61
本文介绍了如何在列表中查找嵌套列表的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The function takes a list and returns an int depending on how many lists are in the list not including the list itself. (For the sake of simplicity we can assume everything is either an integer or a list.)

例如:

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

count_list(x) # would return 8

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

I think using recursion would help but I am not sure how to implement it, this is what I have so far.

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]))

推荐答案

这似乎可以完成工作:

def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count

这篇关于如何在列表中查找嵌套列表的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆