使用数据类"'type' object is not subscriptable"



尝试将数据从csv文档输入到数据类中。

from dataclasses import dataclass
@dataclass
class deck:
name:str = ''
length:float = 0.0
width:float = 0.0
cost:int = 0
def read(deck):
with open("Deckingcsv.csv", "r") as d:
line = d.readline().rstrip('n') 
counter = 0
while line:
items = line.split(',') 
print(items)
deck[counter].name = items[0] 
deck[counter].length = items[1]
deck[counter].width = items[2]
deck[counter].cost = items[3]
line = d.readline().rstrip('n') #separates another line
counter += 1
return deck

read(deck)
print(deck)

CSV文件为:

Themon,3.2,2.3,450
Larrec,3.4,3,700
Medrec,2.1,2,500
Parallel,5,4,825
Suncatch,3,3,400
Chantran,9,6,975

但是,这会返回以下错误:TypeError: 'type' object is not subscriptable, line 18我不太清楚这个错误的原因,任何帮助都将是感激的:)

deck是一个类。如果你想创建一副牌的项目,试试这个:

from dataclasses import dataclass
@dataclass
class Item:
name:str = ''
length:float = 0.0
width:float = 0.0
cost:int = 0
def read(deck):
with open("Deckingcsv.csv", "r") as d:
line = d.readline().rstrip('n') 
counter = 0
while line:
items = line.split(',') 
print(items)
item = Item(items[0],items[1],items[2],items[3]
deck.append(item)
line = d.readline().rstrip('n') #separates another line
counter += 1
return deck
deck = []
read(deck)
print(deck)

相关内容

  • 没有找到相关文章

最新更新