2017-08-25 88 views
0

我正在使用函数来编码购物清单。用户被问到诸如对象的名称,数量,他们将从中购买商店以及它的价格等问题。这些然后被添加到一个csv文件。用户可以询问总价,以便他们知道他们将花多少钱。TypeError:列表索引必须是整数,而不是功能元组

这里是我的代码:

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 

下面是其他代码correspomds的问题:

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 
+2

'ViewItem [i] [3]' – Barmar

+1

你有一个名为TotalCost()的函数和一个名为TotalCost的变量... –

+1

@ReblochonMasque我猜他只调用'TotalCost()'一次,所以它从来没有注意到运行后他不能再调用它。 – Barmar

回答

1

的语法访问嵌套列表中的元素是

variable[1stindex][2ndindex][3rdindex]... 

所以它应该是:

TotalCost=TotalCost+int(ViewItem[i][3]) 

1,3是一个元组,这是不能被用作一个列表索引。

相关问题