如何将字典中二维列表的一列中的所有元素相加? Python 3
How to add up all of the elements in a column of a 2d list within a dictionary? Python 3
我的代码是一个字典,其值是二维列表。我需要编写一个函数来计算字典中每个列表中所有相同索引号的总和。这是我目前所拥有的:
def totalQty(theInventory):
totalQuantity = 0
for key in theInventory:
for book in key:
totalQuantity += book[3]
theInventory 是字典,book 是字典中存储的每一个列表。我不断收到此错误:
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]
键变量是键名的字符串,不是列表
我的代码是一个字典,其值是二维列表。我需要编写一个函数来计算字典中每个列表中所有相同索引号的总和。这是我目前所拥有的:
def totalQty(theInventory):
totalQuantity = 0
for key in theInventory:
for book in key:
totalQuantity += book[3]
theInventory 是字典,book 是字典中存储的每一个列表。我不断收到此错误:
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]
键变量是键名的字符串,不是列表