第6章-6 求指定层的元素个数
输入一个嵌套列表,再输入层数,求该层的数字元素个数。
输入格式:
第一行输入列表 第二行输入层数
输出格式:
在一行中输出元素个数
输入样例:
在这里给出一组输入。例如:
[1,2,[3,4,[5,6],7],8]
3
输出样例:
在这里给出相应的输出。例如:
2
x = eval(input())
n = int(input())
def Sum(x, count, weight):
for ch in x:
if isinstance(ch, int) and weight == n:
count += 1
for ch in x:
if isinstance(ch, list):
count = Sum(ch, count, weight+1)
return count
print(Sum(x, 0, 1))
另解:
a = eval(input())
b = int(input())
def sum(n, j):
sums = 0
if isinstance(n, int) and j == b:
sums += 1
if isinstance(n, list):
for i in n:
sums += sum(i, j + 1)
return sums
print(sum(a, 0))