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)
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)
这是一个非递归的解决方案:
代码:
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)