python列表元素求和isinstance,Python中嵌套列表的总和

本文档介绍了一个关于如何在Python 3.3中处理嵌套列表求和的问题,分享了使用isinstance()检查元素类型并正确迭代的解决方案。通过实例代码演示了如何避免因变量名冲突和列表元素类型问题导致的错误。
摘要由CSDN通过智能技术生成

I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :

def nested_sum(L):

sum=0

for i in range(len(L)):

if (len(L[i])>1):

sum=sum+nested_sum(L[i])

else:

sum=sum+L[i]

return sum

The above code gives following error:

object of type 'int' has no len()

I also tried len([L[i]]), still not working.

Anyone can help? It is Python 3.3

解决方案

You need to use isinstance to check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler.

def nested_sum(L):

total = 0 # don't use `sum` as a variable name

for i in L:

if isinstance(i, list): # checks if `i` is a list

total += nested_sum(i)

else:

total += i

return total

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值