【发布时间】:2022-01-17 06:14:41
【问题描述】:
我正在尝试使用程序方法而不是面向对象的方式在 Python 中创建一个商店,然后我创建了这个函数,它使用商店库存读取我的 CSV 文件,除了包含“现金”的 CSV 文件的第一行可在商店购买。
我试图然后访问价格和数量,但我得到了错误:
p=(row[0], float(row[1]))
IndexError: list index out of range
这是我的参考代码:
def createAndStockShop():
s=Shop()
with open("Stock.csv")as csv_file:#reading our stock file
csv_reader=csv.reader(csv_file,delimiter=',')#creating csv reader variable setting up delimiter as ","
first_row=next(csv_reader)
s.cash=(first_row[0])#extracting shop cash from first row of the file
for row in csv_reader:#using for loop to go through the file
p=(row[0], float(row[1]))
ps=ProductStock(p,float(row[2]))
s.stock.append(ps)
print(ps)
return s#returning shop
作为参考,文件“Stock.csv”的外观如下: csv file I am opening in with this code and containing my stock
此外,这些是我为 Product stock 和 shop 创建的类以提供更多上下文:
@dataclass #Creating first data class for Products in shop
class Product:
name: str #values are "name" as string and price as float to include decimals
price: float = 0.0
@dataclass #Creating data class for the stock in shop
class ProductStock:
product:Product
quantity:int
@dataclass #Dataclass for shop, values cash as a float and stock as list
class Shop():
cash: float = 0.0
stock: List[ProductStock] = field(default_factory=list)
【问题讨论】:
-
那么,
row中有什么内容? -
为什么不直接打印
row看看为什么row[0]或row[1]会失败? -
您的 CSV 文件中很可能存在空值/行。在代码中读取这些值时,会导致错误。
-
请不要发布数据图像 - 将其复制并粘贴为文本,然后将其格式化为代码。通常,我们需要复制您的数据来测试您的代码和测试我们的解决方案——我们不能用图像来做到这一点。
标签: python csv python-dataclasses