You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套列表求和故障:计算利润与数量总和时输出空列表求修复

问题修复方案

原代码存在三个关键错误:

  • 循环遍历的变量写错了:用了未定义的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:55:11