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

Python sum函数报TypeError: 'int' object is not iterable错误解决

问题诱因

报错的直接原因是sum()函数的参数必须是可迭代对象(列表、元组、生成器等可遍历的结构),但line_holder.count()方法的返回值是单个整数——代表传入的匹配项在line_holder中的出现次数。你把单个整数传给sum(),函数尝试遍历这个整数做累加时,就会触发'int' object is not iterable的类型错误。
除此之外代码还有一个隐藏逻辑问题:当前定义的Mitchell_Trubisky_rec是包含三个元素的元组("Mitchell Trubisky for ", x, " yards"),如果line_holder中存储的是拼接完成的整句字符串,这个元组永远无法匹配到对应内容,即使修复了sum的报错,统计结果也会全部为0。

修复方案

根据实际需求二选一即可:

  • 如果需要逐次打印1到100每个码数对应的记录出现次数,直接移除多余的sum()包装,同时把匹配项改为和line_holder存储格式一致的完整字符串即可,参考代码:
for x in range(1, 101):
    Mitchell_Trubisky_rec = f"Mitchell Trubisky for {x} yards"
    current_count = line_holder.count(Mitchell_Trubisky_rec)
    print(current_count)
  • 如果需要把1到100所有码数对应的出现次数累加,得到总的记录数/总码数,需要先初始化一个总计数变量,在循环中逐次累加每个x对应的count结果,参考代码:
Mitchell_Trubisky_Recyds = 0
for x in range(1, 101):
    Mitchell_Trubisky_rec = f"Mitchell Trubisky for {x} yards"
    Mitchell_Trubisky_Recyds += line_holder.count(Mitchell_Trubisky_rec)
print(Mitchell_Trubisky_Recyds)

内容的提问来源于stack exchange,提问作者Mark Silkworth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 21:45:41