How to find the number of nested lists in a list?

后端 未结 6 2065
余生分开走
余生分开走 2020-12-17 11:02

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

6条回答
  •  半阙折子戏
    2020-12-17 11:37

    You can do it with a recursion function :

    def count(l):
        return sum(1+count(i) for i in l if isinstance(i,list))
    

    Demo:

    >>> x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
    >>> count(x)
    8
    

提交回复
热议问题