2017-12-02 89 views
0

我的代码是一个值为2d列表的字典。我需要编写一个函数,将字典中每个列表中的所有索引号加起来。以下是我迄今为止:如何在字典中的2d列表的列中添加所有元素? Python 3

def totalQty(theInventory): 

totalQuantity = 0 

for key in theInventory: 
    for book in key: 
     totalQuantity += book[3] 

theInventory是字典和书籍是存储在字典中的每个列表。我不断收到此错误:

builtins.IndexError: string index out of range 

回答

2

在字典for key in theInventory不给你的每个元素,但每个元素的关键,所以你必须通过theInventory[key]

你也可以使用for key, value in theInentory.items()访问的元素。然后你可以遍历value

尝试:

for key, value in theInventory.items(): 
    for book in value: 
     totalQuantity += int(book[3]) 
+0

我越来越:builtins.TypeError:不支持的操作数类型(S)+ = :'int'和'str' – gumbo1234

+0

'book [3]'中的内容是什么?有点像'1'或''1''吗? – Tekay37

+0

本书[3]只是一个从文件中的整数,所以应该只是1 – gumbo1234

0
def totalQty(theInventory): 
totalQuantity = 0 
for key in theInventory: 
    totalQuantity += theInventory[key][3] 

的关键变量是关键名的字符串不是列表

相关问题