【问题标题】:Trying to iterate over floats in a dictionary试图迭代字典中的浮点数
【发布时间】: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


【解决方案1】:

您不必遍历 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

正如 cmets 中也提到的,将函数更改为单行函数可能更容易,这样您就可以避免 for 循环

def add_prices(basket):
    return round(sum(basket.values()), 2)
add_prices(groceries)
#28.44

【讨论】:

  • 谢谢您,以供将来参考如何知道何时需要遍历字典中的值
  • 对于普通的字典,如果值存储在列表中,您只需要循环遍历这些值。
【解决方案2】:

你不必要地做另一个循环。您可以直接添加价格。 了解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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案4】:

    遍历字典的方法

    假设我们有一本字典

    groceries = {"banana": 0.99, "milk": 3.99, "eggs": 2.99}
    

    这是我们可以迭代它的方法

    1. 遍历键
    for item in groceries:
        print(item)
    

    结果:

    banana
    milk
    eggs
    
    1. 迭代值
    for price in groceries.values():
        print(price)
    

    结果

    0.99
    3.99
    2.99
    
    1. 迭代键、值对
    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(即香蕉的成本)似乎是合理的。在这个问题中,尽管您只是合计价格,而不管商品是什么。因此,您不需要键,只需要值。

    如果您只是想知道购物清单上的物品,那么您将只遍历键。

    【讨论】:

      【解决方案5】:

      当您可以直接执行此操作时,我不知道您为什么在主循环中执行第二个循环:

      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) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-07
        • 1970-01-01
        • 2013-02-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多