我正在为我的大学班级创建一个程序,将商品添加到购物车并显示总价格和数量。这是我的示例代码。之后我会将这些信息传输到一个类文件中:shop_cart = {}item_quantity = int(input('How many items? '))print()for i in range(item_quantity): print('Item #', i+1, sep=' ') item_name = str(input('Item Name: ')) item_price = float(input('Item Price: ')) shop_cart[item_name] = item_price item_quantity = int(input('Item Quantity: ')) shop_cart[item_name] = item_price, item_quantity print()print('Shopping Cart: ', shop_cart)print() remove = str(input('Do you want to remove items? (Y/N): '))if remove == 'Y': remove_item = int(input('How many items to remove? ')) for i in range(remove_item): remove_name = str(input('Enter item name to be removed: ')) del shop_cart[remove_name] print(remove_name, 'has been removed from shopping cart.')print()print('Shopping Cart: ', shop_cart)print('Checking out')我有麻烦乘以item_price通过item_quantity,然后将所有的值加在一起来创建一个“总价值”对象。
2 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
由于您的字典中的值是元组,您可以获取所有这些值,.values()然后使用它们sum来添加每个元组的所有产品:
print('Shopping Cart: ', shop_cart)
print('Total: ', sum(price * quantity for price, quantity in shop_cart.values()))
输出
Shopping Cart: {'Banana': (1.0, 6), 'Apple': (2.0, 5)}
Total: 16.0
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
from itertools import starmap
import operator as op
total = sum(starmap(op.mul, cart.values())
添加回答
举报
0/150
提交
取消