嵌套列表求和故障:计算利润与数量总和时输出空列表求修复
问题修复方案
原代码存在三个关键错误:
- 循环遍历的变量写错了:用了未定义的
int1,应该替换成目标列表cluster1 - 多余且错误的类型判断:
profit和quantity已经是单个数值(每个子列表拆出来的元素),isinstance((profit,quantity), list)永远为False,导致代码块从未执行 - 错误使用
sum():单个数值不需要用sum(),直接累加即可
修复后的代码(循环累加版本):
cluster1=[[1,2],[1,6],[9,0]] totalprofit1 = 0 totalquantity1 = 0 for profit, quantity in cluster1: totalprofit1 += profit totalquantity1 += quantity print(totalprofit1) # 输出11 print(totalquantity1) # 输出8
如果想用更简洁的写法,可以用生成器表达式直接求和:
cluster1=[[1,2],[1,6],[9,0]] totalprofit1 = sum(item[0] for item in cluster1) totalquantity1 = sum(item[1] for item in cluster1) print(totalprofit1) # 输出11 print(totalquantity1) # 输出8
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

