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

如何使用csv.DictReader将行内除首列外的列值转为int类型

问题原因

csv.DictReader读取返回的每一行是字典结构,键对应CSV首行的表头字段名,值为对应列的字符串内容,本身不支持列表式的数字索引切片。你写的row[1:]会把切片对象当做字典的键去查询,而切片对象不可哈希,才会抛出对应的错误。

无硬编码实现方案

不需要手动写死每一列的列名,直接通过DictReader自带的fieldnames属性就能拿到所有列名的有序列表,自动定位除第一列外的所有目标列,代码如下:

import csv
import sys

filename = sys.argv[1]
database = []
with open(filename, newline='', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    # 自动获取除第一列外的所有列名,无需硬编码
    target_cols = reader.fieldnames[1:]
    for row in reader:
        # 遍历目标列做类型转换
        for col in target_cols:
            row[col] = int(row[col])
        database.append(row)

如果不想修改原始读取到的行对象,也可以用字典推导式直接生成处理后的新行:

for row in reader:
    first_col = reader.fieldnames[0]
    processed_row = {first_col: row[first_col]}
    processed_row.update({col: int(row[col]) for col in target_cols})
    database.append(processed_row)

灵活扩展

如果后续需要调整列筛选规则,只需要修改target_cols的生成逻辑即可,不需要改动循环内的转换代码:

  • 要排除指定列名而非固定第一列:target_cols = [col for col in reader.fieldnames if col not in {'列名1', '列名2'}]
  • 要只转换符合命名规则的列:target_cols = [col for col in reader.fieldnames if col.startswith('score_')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:33:41