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

Python筛选特定行列数据遇TypeError,入门新手求助

问题分析与解决

错误原因

你遇到的TypeError: 'int' object is not subscriptable是因为最后筛选数据的循环逻辑完全错误:

  • for row in range(len(table))得到的是整数索引(比如0、1、2...),但你之后用table[row["state"]]试图把整数row当作字典来取值,这就触发了类型错误。
  • 内层的for col in range(len(table[row]))完全多余,因为table里的每个元素都是字典,直接通过键名就能访问值,不需要遍历长度。
  • 开头的for row in flu_data: break会跳过第一行有效数据,应该删掉。

修正后的代码

import csv
# 注意:matplotlib的正确导入方式是导入pyplot模块
import matplotlib.pyplot as plt

table = []

with open('influenza.csv') as file:
    flu_data = csv.reader(file, delimiter=',')
    next(flu_data)  # 跳过表头
    
    # 读取所有数据到字典列表,移除多余的break循环
    for line in flu_data:
        row = {}
        row["state"] = line[0]
        row["url"] = line[1]
        row["website"] = line[2]
        row["activity level"] = line[3]
        row["activity level label"] = line[4]
        row["weekend"] = line[5]
        row["week"] = line[6]
        row["season"] = line[7]
        table.append(row) 

# 筛选目标数据:直接遍历每个字典元素
target_data = []
for item in table:
    # 直接通过字典键名判断条件
    if item["state"] == "North Carolina" and item["season"] == "2012-13":
        target_data.append(item)

# 打印筛选结果
print("北卡罗来纳州2012-13赛季流感数据:")
for data in target_data:
    print(data)

关键优化点

  • 直接遍历table中的字典元素而非索引,彻底避免类型错误。
  • 用target_data单独存储筛选结果,方便后续绘图调用。
  • 修正了matplotlib的导入错误(原代码import matplotlib as plt无法直接调用绘图功能)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:37