【问题标题】:Computing shopping-list total using dictionaries [duplicate]使用字典计算购物清单总数[重复]
【发布时间】:2015-03-22 01:27:42
【问题描述】:

我尝试调用列表中制作的购物清单的字典值总和,但出现错误并且总和为 10.5 而不是 7.5,它应该给出列表中物品的总价格,任何列表.

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!

def compute_bill(food):
    total = 0
    for item in food:
        item = shopping_list(prices[key])
        total += item
    return total
shopping_list = ["banana", "orange", "apple"]  

【问题讨论】:

  • 那么您是否要将库存数量乘以价格并加上小计?
  • 这是你的全部代码吗?你从来没有真正调用 compute_bill,所以这根本不应该给你任何输出。
  • 函数应该作为参数是什么?什么是关键变量?
  • 你可能想执行compute_bill(shopping_list)
  • 顺便问一下,这是什么教科书问题?这至少是第三次在 SO 上被问到:stackoverflow.com/questions/16087118/…stackoverflow.com/questions/19547281/…

标签: python list dictionary shopping


【解决方案1】:

您可以使用列表推导 ...

sum([ prices[s] for s in shopping_list ])

【讨论】:

  • 迄今为止最 Pythonic 和优雅的!您只需要sum( min(stock[item],count) * prices[item] for item,count in Counter(shopping_list).items() ) 来强制您销售的商品不能超过库存。
  • 好吧,我在想自己如果任何地方都不需要,他们为什么要告诉我们库存数量?
【解决方案2】:

我假设您要计算项目列表的总成本。

您的现有代码存在一些问题:

  • shopping_list 是字典,而不是函数或类(或“可调用”)。您可以使用shopping_list[key] 访问其中的项目
  • 你正在做for item in foods,但你随后分配给item。这可能不是您想要的。
  • key 不存在于您的代码中,除了prices[key]

我认为您希望为您的 compute_bill 函数提供类似的功能:

def compute_bill(food):
    total = 0
    for item in food:
         total += prices[item]
    return total

然后您可以使用compute_bill(shopping_list) 调用它。此函数现在将返回 7.5(这是您要查找的结果)。

【讨论】:

    【解决方案3】:

    您的代码和此处的其他所有人都忽略了stock,因此它可以销售比库存更多的商品;大概这是一个错误,您应该强制执行该限制。有两种方法:

    迭代方法:for item in food:...检查stock[item]是否>0,如果是,则添加价格,减少stock[item]。但是您可以简单地将每个项目计数相加,然后用库存计数计算 min()。

    更 Pythonic 和更短:

    # Another test case which exercises quantities > stock
    shopping_list = ["banana", "orange", "apple", "apple", "banana", "apple"]
    
    from collections import Counter    
    counted_list = Counter(shopping_list)
    # Counter({'apple': 3, 'banana': 2, 'orange': 1})
    
    total = 0
    for item, count in counted_list.items():
        total += min(count, stock[item]) * prices[item]
    

    或作为单行:

    sum( min(stock[item],count) * prices[item] for item,count in Counter(shopping_list).items() )
    

    【讨论】:

      【解决方案4】:

      您的代码看起来很奇怪,但这有效:

      def compute_bill(food):
          total = 0
          for item in food:
              total += prices[item]
          return total
      
      shopping_list = ["banana", "orange", "apple"] print
      compute_bill(shopping_list)
      

      我假设您想使用 prices 字典来计算您的 shopping_list 中商品的价格。

      如果你需要任何帮助,可以问我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多