我正在为我的大学类(class)创建一个程序,将商品添加到购物车并显示总价格和数量。这是我的示例代码。之后我会将这些信息传输到一个类文件中:
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
,然后将所有值加在一起以创建“总值(value)”对象。
最佳答案
由于字典中的值是元组,因此您可以使用 .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
关于python - 将字典中的值添加到一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253779/