python - 添加到购物篮,并从库存中取出等值产品

标签 python dictionary python-3.4 shopping-cart

在Python 3上

嗨,我有一批产品(作为字典。其中每个键都是标识号,每个值都是信息字典)。该程序接收一个标识号(想要的产品)和所需的数量。 然后代码应该将产品信息添加到空购物篮中,将库存数量编辑为原始数量减去输入的数量。并将购物篮中的金额编辑为所需的金额。

但是,代码始终使库存输出中的产品数量为零。并且购物篮中的产品数量也输出为零。

通过打印命令我想我已经找到了问题所在。下面的 if 语句中的某处。

但它看起来很简单,我不知道我错在哪里!

提前非常感谢。库存和“漂亮”的打印函数位于代码顶部,可帮助您可视化情况

            stock = {
                '10005' : {
                        'name' : 'Conference Pears Loose',
                        'price' : 2.00,
                        'unit' : 'kg', 
                        'promotion' : None,
                        'group' : None,
                        'amount' : 1.550
                 },
                 '10013' : {
                        'name' : 'Emmental Slices 250G',
                        'price' : 1.75,
                        'unit' : 'pieces', 
                        'promotion' : 'get2pay1',
                        'group' : None,
                        'amount' : 9
                 },
                 '10015' : { 
                        'name' : 'Diced Beef 400G', 
                        'price' : 4.50,
                        'unit' : 'pieces', 
                        'promotion': 'get4pay3',
                        'group' : 4,
                        'amount' : 14
                }}

            def listitems(dct):
                """
                inputs dictionary of stock and prints a lovely table showing all the items with info
                """
                print("\n")
                print(" {0:^5} | {1:<38} | {2:^7} | {3:^11} ".format("Ident", "Product", "Price", "Amount"))
                print("-" *7 + "+" + "-" * 40 + "+" + "-" * 9 + "+" + "-"*12 + "+")
                for key in sorted(dct):
                    print(" {:^5} | {name:<38} | {price:>5.2f} £ |  {amount:>} {unit:<14}".format(key, **dct[key]))
                return


            #main code of function



            basket = dict()
            quantity = input("Number of items? ")
            #amount = 6
            ident = input("Indentification number? ")
            #ident = "10011"

            listitems(stock)


            try:
                quantity = int(quantity)
            except ValueError:
                try:
                    quantity =  float(quantity)
                except ValueError:
                    print("You have entered a invalid amount")       

            try:
                ident = str(ident)
            except ValueError:
                print("you have entered a invalid indent.")


            #print("amount is ", quantity)
            #print("amount in stock ", stock[ident]["amount"])



            if quantity > 0:
                if quantity < stock[ident]["amount"]:

                    basket[ident] = stock[ident] #adding the product tp the basket. 

                    basket[ident]["amount"] = quantity

                    stock[ident]["amount"] = stock[ident]["amount"] - quantity





            listitems(stock)
            listitems(basket)


            print("amount is ", quantity)
            print("amount in stock ", stock[ident]["amount"])
            print("amount in basket", basket[ident]["amount"])

最佳答案

 basket[ident] = stock[ident]

这就是你的问题,存在可变类型,所以这不会产生两个相同的东西,而是一个具有两个不同名称的东西。

 basket[ident]["amount"] = quantity # ok with that
 # since basket[ident] and stock[ident] are now the same you just subtract the amount you just set to itself
 stock[ident]["amount"] = stock[ident]["amount"] - quantity

要做你想做的事,你必须明确表示你想要一份副本:

 basket[ident] = stock[ident].copy()

关于python - 添加到购物篮,并从库存中取出等值产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863848/

相关文章:

algorithm - 等簇大小的 K-means 算法变体

python - 在谷歌应用程序引擎中加载cookie

Windows : ImportError: No module named 'pip' 上的 Python 3.3.4 和 virtualenv 创建

python - 让 Django 与 Apache 一起工作

python - scikit-learn:计算并绘制递归 KBEST 特征 (k ='all' ) 性能

用于在长列表中查找唯一名称的 Python 命令

python - 如何找到 pandas 中每一对后续 DataFrame.index 值之间的差异?

python - python中的嵌套字典在访问不存在的键时出错

python - python 和 regex 模块如何处理反斜杠

python - Python 中的函数定义和调用