Python TypeError:列表索引必须是整数,而不是带有函数的元组
我正在使用函数来编写购物清单。用户会被问到诸如物品名称、数量、他们将从哪家商店购买以及价格等问题。然后将这些文件添加到csv文件中。用户可以询问总价格,以便了解他们将花费多少 这是我的密码:Python TypeError:列表索引必须是整数,而不是带有函数的元组,python,function,csv,Python,Function,Csv,我正在使用函数来编写购物清单。用户会被问到诸如物品名称、数量、他们将从哪家商店购买以及价格等问题。然后将这些文件添加到csv文件中。用户可以询问总价格,以便了解他们将花费多少 这是我的密码: def TotalCost(): ViewItem = ViewList() with open ("C:\\Users\\sophie\\Documents\\Sophie\\Homework\\Year 11\\Computer Science\\ShoppingList.csv") as csvfil
def TotalCost():
ViewItem = ViewList()
with open ("C:\\Users\\sophie\\Documents\\Sophie\\Homework\\Year 11\\Computer Science\\ShoppingList.csv") as csvfile:
readcsv = csv.reader(csvfile)#delimeter=',')
TotalCost=0
for i in range(1,3):
TotalCost=TotalCost+int(ViewItem[i,3])
def ViewList():
with open ("C:\\Users\\sophie\\Documents\\Sophie\\Homework\\Year 11\\Computer Science\\ShoppingList.csv") as csvfile:
reader=csv.reader(csvfile)#,delimeter=',')
for row in reader:
ItemView.append(row)
return ItemView
以下是与问题对应的其他代码:
elif ModeChose=='C':
TotalCost()
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\sophie\Documents\Sophie\Homework\Year 11\Computer Science\ShoppingList.py", line 106, in <module>
TotalCost()
File "C:\Users\sophie\Documents\Sophie\Homework\Year 11\Computer Science\ShoppingList.py", line 18, in TotalCost
TotalCost=TotalCost+int(ViewItem[i,3])
TypeError: list indices must be integers, not tuple
访问嵌套列表中元素的语法为
variable[1stindex][2ndindex][3rdindex]...
因此,它应该是:
TotalCost=TotalCost+int(ViewItem[i][3])
1,3是一个元组,不能用作列表索引。ViewItem[i][3]您有一个名为TotalCost的函数和一个名为TotalCost的变量…@ReblochonMasque我猜他只调用了TotalCost一次,因此它不会注意到在运行后不能再次调用它。TotalCost可能是一个隐藏函数名的局部变量,这将阻止递归调用,但在其他方面是无害的。很难判断压痕是否断裂。也许巴尔马,正如切普纳所指出的,很难判断。。。