【问题标题】:how to decrease dictionary items by one when item is added to the cart in python如何在python中将项目添加到购物车时将字典项目减一
【发布时间】:2014-06-30 03:06:48
【问题描述】:

我想要做的是在 python 中创建一个函数来将添加到购物车的物品的总价格相加,如果该物品在股票字典中可用。同时,如果该项目可用并添加到总数中,我想将该字典中的项目数量减少添加到购物车的数量。

我完全卡住了,我不知道如何前进,请看下面的代码:

stock = {
    "item1": 6,
    "item2": 0,
    "item3": 32,
    "item4": 15
}

prices = {
    "item1": 4,
    "item2": 2,
    "item3": 1.5,
    "item4": 3
}

def compute_bill(cart):
    total = 0
    for key in cart:
        if stock[key] > 0:
            total += prices[key] 
        return total

【问题讨论】:

  • 我希望 compute_bill 在遍历购物车中的所有项目之后返回总数,而不是仅在第一个之后。也就是说,你应该突出return total

标签: python dictionary


【解决方案1】:

假设,没有作为问题的一部分说明,购物车字典的值是所需的那种物品的计数,我会这样编写代码:

def compute_bill(cart):
    total = 0
    for key, value in cart.items():
        if 0 < value <= stock[key]:
            total += prices[key] * value
            stock[key] -= value
    return total

如果您有 stockpricecart 的这些值:

stock = {
    "item1": 6,
    "item2": 0,
    "item3": 32,
    "item4": 15
}

prices = {
    "item1": 4,
    "item2": 2,
    "item3": 1.5,
    "item4": 3
}

cart = {
    "item1": 8,
    "item2": 3,
    "item3": 10,
    "item4": 10
}

那么这里是购物车的价格:

>>> print compute_bill(cart)
45.0
>>> from pprint import pprint
>>> pprint(stock)
{'item1': 6, 'item2': 0, 'item3': 22, 'item4': 5}

请注意 item1 并没有减少,因为订单无法全部填写。同样,item2 缺货且未填充。买家有 item3 和 item4 各 10 个。这两件商品的库存减少了 10 件。

此外,这避免了negative cart quantity bug that Amazon had

【讨论】:

  • 谢谢,如何调用这个函数并打印出来?
  • 非常感谢!!!这真太了不起了。我希望我能像你一样知道这些东西。我现在才刚学,几周前就开始学了。再次感谢。
  • 现在我想知道如何设置它以根据用户输入确定购物车项目。我应该把这个作为一个新问题来问吗?我实际上想弄清楚我自己,但如果你能给我一些指示,我将不胜感激,这样我至少会理解如何做到这一点的基本概念。
【解决方案2】:

您可以简单地减少该商品的库存数量:

def compute_bill(cart):
    total = 0
    for key in cart:
        if stock[key] > 0:
            total += prices[key] 
            stock[key] -= 1
        return total

【讨论】:

  • 谢谢,我也是这么想的,但我想知道如果我只返回总计,这还会返回库存的减少[key]吗?最好的检查方法是我猜我是否完成了代码并打印它,但我仍在试图弄清楚如何做到这一点,我只是在学习 python,所以还是有点迷茫
  • @JoeRay,这仍然会减少库存数量。仅仅因为你不返回它并不意味着你没有减少价值。就像你所说。尝试在前后打印库存以了解发生了什么。很高兴我能帮上忙。
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
相关资源
最近更新 更多