Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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

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

For example:

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]))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a recursion function as following:

In [14]: def count(l):
    ...:     return sum(1 + count(i) for i in l if isinstance(i,list))
    ...: 

In [15]: 

In [15]: x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

In [16]: count(x)
Out[16]: 8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...