Python实现商城购物经典案例

发布时间 2023-08-18 17:04:15作者: 小甘要努力了

 

代码分步骤思路:

商城添加商品:

opea_db = [{'store_name': '手机','num': 1}]
while True:
    store_name=input('请输入需要存放的商品(按1退出添加1):')
    # def f(o):
    #     list(filter(f,opea_db))  # 输出每个字典
    def f(i):
        if i['store_name']==store_name:
           num=i['num']+1
           i['num']=num
           return i
        else:
            # 新添加的商品数量默认为0 没有库存
            opea_db.append({'store_name':store_name,'num':0})

    list(filter(f,opea_db))
    print(opea_db)

 

或者这样写:
while True:
    store_name=input('请输入需要存放的商品(按1退出添加1):')
    # def f(o):
    #     print(o)
    # list(filter(f,opea_db))  # 输出每个字典
    for i in opea_db:
        if i['store_name']==store_name:
                num=i['num']+1  # 在默认值基础上增加
                # print(num)
                i['num']=num
        else:
            opea_db.append({'store_name': store_name,'num':0 })

    print(opea_db)

 

  

 

 

运行截图:

 此写法缺陷:

增加新的商品且再次增加对应数量的话打印输出只显示最终商品数量,不要把前一次数量信息都显示出来,重复!

# 新添加的商品数量默认为0 没有库存
            opea_db.append({'store_name':store_name,'num':0})   # 此部分没有过滤器过滤,导致输出存在重复

代码优化:新增商品

opea_db = [{'store_name': '手机','num': 1}]
while True:
    store_name=input('请输入需要存放的商品(按1退出添加1):')
    # def f(o):
    #     list(filter(f,opea_db))  # 输出每个字典
    def f(i):
        if i['store_name']==store_name:
           num=i['num']+1
           i['num']=num
           return i
    #     else:
    #         # 新添加的商品数量默认为0 没有库存
    #         opea_db.append({'store_name':store_name,'num':0})
    #
    # list(filter(f,opea_db))
    # print(opea_db)

    # 如果新添加商品(i['store_name']不等于store_name)没有返回值return 就None =====假的
需要执行否定语句,即下述代码 ---添加商品 if not list(filter(f,opea_db)): # opea_db.append({'store_name':store_name,'num':1}) opea_db.append({'store_name': store_name,'num': 1}) print(opea_db)

运行截图: