文章翻译自: https://stackoverflow.com/questions/26877186/how-to-find-the-number-of-nested-lists-in-a-list
转载自:http://www.voidcn.com/article/p-ydyzomhy-bts.html
- 该函数需要一个列表,并返回一个int,取决于列表中不包括列表本身的列表数量. (为了简单起见,我们可以假设一切都是一个整数或一个列表.
x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
count_list(x) # would return 8
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
- You can do it with a recursion function :
def count(l):
return sum(1+count(i) for i in l if isinstance(i,list))
3.You can do it with a recursion function :
def count(l):
return sum(1+count(i) for i in l if isinstance(i,list))
3.Demo:
>>> x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
>>> count(x)
8