假设lst=[3,4,12,[6,9,12,24],[12,18,34]]统计list中包含元素12的个数
lst = [3, 4, 12, [6, 9, 12, 24], [12, 18, 34]]
def count(ls):
c = 0
for i in ls:
if type(i) == int:
if i == 12:
c += 1
else:
c += count(i)
return c
print(count(lst))
def count(lst, target):
n = 0
for i in lst:
if i == target:
n += 1
elif type(i) is list:
n += count(i, target)
return n
lst=[3,4,12,[6,9,12,24],[12,18,34]]
b=count(lst, 12)
print(b)