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

Python使用dataclass处理CSV数据报'type' object is not subscriptable如何解决

报错原因

  • 第18行deck[counter].name = items[0]中的deck是你定义的类对象,不是存储该类实例的列表,类对象本身不支持下标([])访问操作,因此触发类型错误。
  • 你调用read(deck)时传入的是deck类本身,而非预先初始化的实例列表,同时也没有对deck[counter]预先实例化就直接赋值属性,逻辑不成立。
  • 额外问题:CSV读取到的字段都是字符串类型,没有转为length/width对应的浮点型、cost对应的整型,后续使用会存在类型不符的问题。

修正后代码

from dataclasses import dataclass

@dataclass
class Deck:
    name: str = ''
    length: float = 0.0
    width: float = 0.0
    cost: int = 0

def read_deck_list():
    deck_list = []
    with open("Deckingcsv.csv", "r", encoding='utf-8') as d:
        for line in d:
            line = line.rstrip('\n')
            if not line:
                continue
            items = line.split(',')
            cur_deck = Deck(
                name = items[0],
                length = float(items[1]),
                width = float(items[2]),
                cost = int(items[3])
            )
            deck_list.append(cur_deck)
    return deck_list

if __name__ == '__main__':
    all_decks = read_deck_list()
    for deck in all_decks:
        print(deck)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 03:15:00