如何从列表提取字典并计算购物清单小计总计?解决NoneType问题
购物清单计算问题解决
一、为什么index1是NoneType?
你写的代码:
ındex1 = print(shopping_list["items"][0]["price"]) print(type(ındex1))
输出<class 'NoneType'>的原因是:print()函数本身没有返回值,它只是将内容输出到控制台,所以把print()的结果赋值给变量时,变量会被赋值为None。
正确的写法应该是先获取值,再打印:
index1 = shopping_list["items"][0]["price"] print(index1) print(type(index1)) # 此时会输出 <class 'float'>
二、完整实现购物清单小计与总计计算
以下是实现需求的完整代码,能生成符合预期的输出结构:
# 原始购物清单 shopping_list = { "items": [ {"product_id": 1, "price": float(20.1), "quantity": int(5)}, {"product_id": 2, "price": 21.2, "quantity": 3}, {"product_id": 3, "price": 33.4, "quantity": 2} ] } # 计算每个商品的小计及总金额 total = 0.0 for item in shopping_list["items"]: subtotal = item["price"] * item["quantity"] item["subtotal"] = subtotal total += subtotal # 添加总计到字典 shopping_list["total"] = total # 打印结果 print(shopping_list)
运行后输出结果:
{'items': [{'product_id': 1, 'price': 20.1, 'quantity': 5, 'subtotal': 100.5}, {'product_id': 2, 'price': 21.2, 'quantity': 3, 'subtotal': 63.6}, {'product_id': 3, 'price': 33.4, 'quantity': 2, 'subtotal': 66.8}], 'total': 230.9}
(注:你预期输出中的总计373.5为计算错误,正确总计应为100.5+63.6+66.8=230.9)
内容的提问来源于stack exchange,提问作者Sena Koç
相关产品推荐
相关产品推荐

