簡體   English   中英

Python 3:在字典中求和

[英]Python 3: Finding the Sum of Values inside a Dictionary

這是我作業上的問題

以下是我解決它的嘗試:

def printStocks(d):
for key, value in d.items() :
    print(key, "\tPrice: ", value[0], "\tAmount: ", value[1])
    sum_items = 0
    sum_items += value[0]*value[1]
print("Total value of all items: ", sum_items)
    
d_1 = {"banana": [4, 5], "apple": [2, 2], "orange": [1.5, 2.5], "pear": [3, 4]}

printStocks(d_1)

雖然調試是這樣的:

Part-2
banana  Price:  4   Amount:  5
apple   Price:  2   Amount:  2
orange  Price:  1.5     Amount:  2.5
pear    Price:  3   Amount:  4
Total value of all items:  12

所以問題是所有項目的總價值應該是 39.75

因為:4x5 + 2x2 + 1.5x2.5 + 3x4 = 39.75;

我不明白為什么它說 12 作為 sum_items 值。 我現在迷路了,可以在這里得到一些幫助。 提前致謝。

您需要將sum = 0置於循環之外。 在其他情況下,每次迭代后它將為零

您在 for 循環的每個循環中重新初始化 sum_items 變量。 您應該將 sum_items = 0 放在 for 循環之外。

暫無
暫無

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

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