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
'''
有人知道怎么做吗? 我只有
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)
请您参考如下方法:
这是一种“肮脏”但简单的方法
def lists(l):
'''
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.
'''
# convert the list to string and count the ['s
# each [ is the start of a list, so the number of ['s equals
# the number of lists
nr_of_lists = str(l).count('[')
# return the number of sublists
return nr_of_lists
不需要递归
