该函数接受一个列表并返回一个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) def lists(A: list) -> int:
'''Return the total number of lists in A (including A itself).
Each element of A and any nested lists are either ints or other lists.
Example:
>>> lists([1, 2, 3])
1
>>> lists([[1], [2], [3]])
4
>>> lists([[[1, 2], [], 3]])
4
'''
Run Code Online (Sandbox Code Playgroud)
有谁知道如何做到这一点?我只有
for i in range(0, len(A)):
if (isinstance(A[i], list)):
count=count+1
return(lists(A[i]))
else:
B=A[i:]
return(count)
Run Code Online (Sandbox Code Playgroud)