簡體   English   中英

如何在字典中的2d列表的列中添加所有元素? Python 3

[英]How to add up all of the elements in a column of a 2d list within a dictionary? Python 3

我的代碼是一個字典,其值為2d列表。 我需要編寫一個函數,將字典中每個列表中的所有相同索引號相加。 這是我到目前為止的內容:

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中的for key in theInventory字典中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]

鍵變量是鍵名稱的字符串而不是列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM