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

Python处理CSV触发TypeError: 'int' object is not iterable报错排查

报错根因

触发TypeError: 'int' object is not iterable的直接原因是:

  • max()、min()是要求入参为可迭代对象(列表、元组、字符串等)的聚合函数,你在代码中先执行max_life = 0把变量设为整数类型,之后又调用max(max_life),相当于给函数传入了单个不可迭代的整数,直接触发类型错误。

除此之外代码还存在多个逻辑错误,即使修复这一处也无法正常统计结果:

  • CSV解析逻辑错误:你把每行的逗号替换为大量空格后,直接通过索引取字符串单个字符,完全没有正确拆分CSV列;life_expectancy = [3]仅定义了一个存储数字3的列表,根本没有读取到真实的预期寿命字段。
  • 变量初始化位置错误:把最大、最小值的初始值写在文件遍历循环内部,每读一行就会把之前统计的结果重置为0,无法完成全数据集统计。
  • 交互逻辑错误:年份查询的input()写在循环内部,每读取一行数据就会弹出一次输入提示,不符合正常交互流程。
  • 比较逻辑错误:统计最小值时误用大于号做判断,结果打印文案也复制错误,将最小值提示写为“max life expectancy”。
修复方案

按照以下逻辑调整代码即可正常运行:

  • 用标准CSV读取方法或split(',')拆分每行数据,不要用替换逗号为空格的错误方式处理,读取到预期寿命字段后转为浮点数类型做数值比较。
  • 把最大、最小值统计变量、年份输入逻辑移到遍历循环外部,遍历前初始化变量,遍历结束后统一打印统计结果。
  • 遍历时跳过CSV表头行,避免把表头文本转为数值触发新的报错。
  • 去掉对整数变量调用max()、min()的错误写法,遍历时直接拿当前行的预期寿命值和已记录的最大、最小值比较更新即可。

修复后的可运行代码:

import csv

welcome = "welcome to the life expectancy data sheet"
print(welcome.upper())

# 遍历前初始化全局统计变量
max_life = -1
max_year = ""
max_country = ""
min_life = float('inf')
min_year = ""
min_country = ""

# 循环外获取用户查询年份,避免重复输入
year_lookup = int(input("Enter the year of interest: "))
year_records = []

with open("life-expectancy.csv", mode="r", encoding="utf-8") as f:
    reader = csv.reader(f)
    next(reader) # 跳过表头
    for row in reader:
        country = row[0]
        code = row[1]
        year = int(row[2])
        life_exp = float(row[3])

        # 更新全局最大值
        if life_exp > max_life:
            max_life = life_exp
            max_year = year
            max_country = country
        
        # 更新全局最小值
        if life_exp < min_life:
            min_life = life_exp
            min_year = year
            min_country = country
        
        # 收集目标年份数据
        if year == year_lookup:
            year_records.append(life_exp)

# 遍历完成后输出结果
print(f"The overall max life expectancy is:{max_life} from {max_country} in {max_year}.")
print(f"The overall min life expectancy is:{min_life} from {min_country} in {min_year}.")

# 如需计算查询年份的平均、最大、最小预期寿命,可放开以下注释
# if year_records:
#     print(f"\nStats for year {year_lookup}:")
#     print(f"Average life expectancy: {sum(year_records)/len(year_records):.2f}")
#     print(f"Max life expectancy: {max(year_records)}")
#     print(f"Min life expectancy: {min(year_records)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 03:48:09