我试图完成这个函数,但无济于事,因为字典中包含浮点值,我试图将其加起来。
这是我目前为止的代码:
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
我完全惊呆了,需要帮助,因为我尝试了类型转换,直接将价格分配给值。
您不必遍历prices
,因为它们已经是float
的值。因此出现浮点数不可迭代的错误信息。
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}
def add_prices(basket):
total = 0
for groceries, prices in basket.items():
total += prices
return round(total, 2)
add_prices(groceries)
#28.44
正如在注释中提到的,将函数更改为一行代码可能更容易,这样可以避免for循环
def add_prices(basket):
return round(sum(basket.values()), 2)
add_prices(groceries)
#28.44
您不必要地执行另一个循环。你可以直接加价格。阅读dict.keys()
,dict.values()
,dict.items
应该是
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():
total += prices
# 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)
print(add_prices(groceries))
>>> 28.44
def add_prices(basket):
# Initialize the variable that will be used for the calculation
total = 0
# Iterate through the dictionary items
for items in basket.values():
total += items
# 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
遍历字典的方法
假设我们有一个字典
groceries = {"banana": 0.99, "milk": 3.99, "eggs": 2.99}
下面是我们如何遍历它的方法
- 遍历键
for item in groceries:
print(item)
结果:
banana
milk
eggs
- 遍历
for price in groceries.values():
print(price)
结果
0.99
3.99
2.99
- 遍历键、值对
for item, price in groceries.items():
print(item, price)
结果
banana, 0.99
milk, 3.99
eggs, 2.99
何时使用每个迭代方法
当我在字典中存储数据时,我通常这样做:使用dict.items
迭代(key, value)
对是最有用的。在这种情况下,键和值都提供了有意义的信息,我想在迭代期间同时使用它们。
杂货作为字典是有意义的,因为同时需要key
(即杂货项目如banana
)和value
(即香蕉的价格)似乎是合理的。在这个问题中,你只是把价格加起来,而不管商品是什么。因此,您不需要键,只需要值。
如果你只想知道购物清单上的商品,那么你只需要迭代键。
我不知道你为什么要在主循环中执行第二个循环,而你可以直接这样做:
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():
total += prices
# Limit the return value to 2 decimal places
return round(total, 2)