如何在字典中的2d列表的列中添加所有元素? Python 3
问题描述:
我的代码是一个值为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
答
在字典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])
答
def totalQty(theInventory):
totalQuantity = 0
for key in theInventory:
totalQuantity += theInventory[key][3]
的关键变量是关键名的字符串不是列表
我越来越:builtins.TypeError:不支持的操作数类型(S)+ = :'int'和'str' – gumbo1234
'book [3]'中的内容是什么?有点像'1'或''1''吗? – Tekay37
本书[3]只是一个从文件中的整数,所以应该只是1 – gumbo1234