对如下嵌套列表中的元素进行求和
code:
def nested_sum(ls):
sum=0
for item in ls:
if isinstance(item,list):
sum+=nested_sum(item)
else:
sum+=item
return sum
if __name__ == '__main__':
l1=list(range(100))
print(nested_sum(l1))
l2=[[1,2],3,[4,5,6]]
print(nested_sum(l2))
l3=[[1,2],[3],[4,5,6]]
print(nested_sum(l3))
l4=[1,2,[3],[4,5,6]]
print(nested_sum(l4))
l5=[[1,2],[3],[4,5,6]]
print(nested_sum(l5))
l6=[[1,2],[3],[4,5,6],[[7,8],9]]
print(nested_sum(l6))
l7=[[1,2],[3],[4,5,6],[[7,8],[9]]]
nested_sum(l7)
print(nested_sum(l7))
结果:
end