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

Python报错TypeError: 'type' object is not iterable,如何修复代码?

Python代码TypeError问题修复

错误原因

你代码里的d = list[int]把传入的参数d覆盖成了list[int]这个类型对象,类型对象无法被遍历,直接触发了TypeError: 'type' object is not iterable。除此之外还有两个问题:

  • sum += i写法错误:sum是列表,单个整数不能直接用+=添加,得用append()方法
  • return(sum)放在for循环内部:第一次循环就会返回结果,函数提前终止,只能处理第一个元素

修改后的代码

根据常见需求,提供两种实现:

1. 计算列表元素的总和

def s(d):
    total = 0
    for i in d:
        total += i
    return total

print(s([1, 2, 3]))  # 输出:6

2. 生成累加过程的列表(逐个元素累加的结果)

def s(d):
    sum_list = []
    current_total = 0
    for i in d:
        current_total += i
        sum_list.append(current_total)
    return sum_list

print(s([1, 2, 3]))  # 输出:[1, 3, 6]

关键修改点

  • 移除d = list[int],直接使用传入的参数d
  • 修正列表元素添加的方式,用append()替代错误的+=
  • 将return语句移到for循环外部,确保遍历完所有元素后再返回结果

内容的提问来源于stack exchange,提问作者Ahmad Altom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:45:48