Python如何对购物车字典内商品的price字段值求和
代码修正与get_total实现
前置逻辑问题说明
你原有代码的核心问题是add_product调用时传入了商品ID数字,而非预先定义的商品字典对象,导致购物车中存储的都是ID值,无法读取price字段计算总价,需要先调整前置函数逻辑,再实现总价计算。
完整可运行代码
# 预先定义商品字典 shoeA = {"id": 342453, "name": "Shoe A", "price": 144.98 } shoeB = {"id": 9800989, "name": "Shoe B", "price": 300} cart = [] # 1.1 添加商品到购物车,times为添加数量 def add_product(product, times): for i in range(times): cart.append(product) print("添加后购物车内容:", cart) # 注意这里传的是商品字典shoeA,而非ID数字 add_product(shoeA, 4) # 1.2 按商品ID删除指定数量的商品 def remove_product(productID, times): count = 0 # 倒序遍历避免删除元素后索引错位 for i in range(len(cart)-1, -1, -1): if cart[i]["id"] == productID and count < times: del cart[i] count +=1 print("删除后购物车内容:", cart) remove_product(342453, 2) # 1.3 查找商品在购物车中的所有索引 def find_product(productID): indexes = [] for i, product in enumerate(cart): if product["id"] == productID: indexes.append(i) print(f"商品ID {productID} 的索引位置:", indexes) return indexes find_product(342453) # 1.4 计算购物车总金额 def get_total(): total = 0.0 for product in cart: total += product["price"] # 保留两位小数符合金额展示习惯 return round(total, 2) # 调用并打印总金额 print("购物车总金额:", get_total())
逻辑说明
get_total的核心逻辑就是遍历购物车列表中的每个商品字典,取出price字段的值累加,最后保留两位小数返回即可。按照你给出的示例,购物车有2件ShoeA时,返回值就是289.96,符合预期。
内容的提问来源于stack exchange,提问作者user16291801
相关产品推荐
相关产品推荐

