[英]Python 3: Finding the Sum of Values inside a Dictionary
This is the question on my homework这是我作业上的问题
Below is my attempt on solving it:以下是我解决它的尝试:
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)
Although the Debug is this:虽然调试是这样的:
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
So the problem is that the total value of all items should be 39.75所以问题是所有项目的总价值应该是 39.75
Since: 4x5 + 2x2 + 1.5x2.5 + 3x4 = 39.75;因为:4x5 + 2x2 + 1.5x2.5 + 3x4 = 39.75;
I don't understand why it says 12 as the sum_items value.我不明白为什么它说 12 作为 sum_items 值。 I am lost right now, could get some little help here.我现在迷路了,可以在这里得到一些帮助。 Thanks in advance.提前致谢。
You need to put your sum = 0
out of loop.您需要将sum = 0
置于循环之外。 In other case it will be zero after every iteration在其他情况下,每次迭代后它将为零
You reinitialize the sum_items variable in each loop in for-loop.您在 for 循环的每个循环中重新初始化 sum_items 变量。 You should put the sum_items = 0 outside the for-loop.您应该将 sum_items = 0 放在 for 循环之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.