【发布时间】:2021-04-27 08:25:39
【问题描述】:
我正在尝试完成此功能,但无济于事,因为字典包含我要总计的浮点值。
这是我目前的代码:
def add_prices(basket):
# Initialize the variable that will be used for the calculation
total = 0
# Iterate through the dictionary items
for groceries, prices in basket.items():
# Add each price to the total calculation
for price in prices:
# Hint: how do you access the values of
# dictionary items?
total += price.values()
# Limit the return value to 2 decimal places
return round(total, 2)
groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59,
"coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44}
print(add_prices(groceries)) # Should print 28.44
我完全傻眼了,需要帮助,因为我尝试将类型转换为直接将价格分配给值。
【问题讨论】:
-
total += price:price已经是一个(浮点)值。同时删除上面的for行,因为prices(将其重命名为price)是单个值。 -
也许更容易使用 sum:
return round(sum(basket.values()), 2): 你的函数已经变成单行了。 -
当卡在这些位置时,请尝试在每个步骤中打印。我会在第一个循环中建议
print(groceries, prices),并注释掉其他所有内容。我相信您将能够弄清楚要添加什么。 -
提示:大量使用
print函数进行调试。例如,print(groceries)和print(prices)直接位于第一行for下方,这对于了解正在发生的事情非常有帮助。
标签: python dictionary iteration