繁体   English   中英

将字典中的值一起添加

[英]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 ,然后将所有值加在一起以创建“总价值”对象。

由于字典中的值是元组,您可以使用.values()获取所有这些.values() ,然后使用sum将每个元组的所有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
from itertools import starmap
import operator as op
total = sum(starmap(op.mul, cart.values())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM