![](/img/trans.png)
[英]Adding together multiple dictionary key values that have the same key string
[英]Adding values in a dictionary together
我正在为我的大学班级创建一个程序,将商品添加到购物车并显示总价格和数量。 这是我的示例代码。 之后我会将这些信息传输到一个类文件中:
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
,然后将所有值加在一起以创建“总价值”对象。
from itertools import starmap
import operator as op
total = sum(starmap(op.mul, cart.values())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.