嵌套dict python中的购物车总价

时间:2018-05-28 16:59:21

标签: python python-3.x

我想用下面的代码计算购物车中的总价格,但我无法在我的商品dict中迭代价格。那里缺少一些东西。另外,如果for循环可以修复,有没有办法使用理解进行迭代?

class ShoppingCart(object):
    def __init__(self):
        self.item = None
        self.quantity = None
        self.price = None
        self.items = {}
    def add(self, item, price, quantity):

        if item in self.items:
            previous_quantity = self.items[item]['quantity']
            previous_price = self.items[item]['price']

            self.items[item] = {'quantity': previous_quantity +   quantity,
                                'price': previous_price + price}
        else:
            self.items[item] = {'quantity':quantity,
                           'price':price}

    def total_items_in_cart(self):
         print(len(self.items))

    def total_items_price_in_cart(self):
         print(sum([price
                 for price in self.items.values()]))

sc = ShoppingCart()
sc.add('book', 30, 1)
# sc.add('book', 132, 1)

sc.add('toothbrush', 4, 10)
# sc.add('toothbrush', 5, 20)

# sc.total_items_in_cart()

cart_price_total = []
for item, value in sc.items.items():
    print("\n{}".format(item))
    for price,qty in value.items():
        print("{} :{}".format(price, qty))
        cart_price_total.append(qty)

print(cart_price_total) # this does not print what I want... 

有没有办法使用理解来获得购物车中的总价值?

编辑:

I added the data using a tuple, and it seems simple now. Cannot figure out why...

class ShoppingCart(object):
    def __init__(self):
        self.item = None
        self.quantity = None
        self.price = None
        self.items = {}
    def add(self, item, price, quantity):
        if item in self.items:
            previous_quantity = self.items[item]['quantity']
            previous_price = self.items[item]['price']
            self.items[item] = (previous_quantity+quantity, previous_price+price)
        else:
            self.items[item] = (price, quantity)

    def total_items_in_cart(self):
         return(len(self.items))

    def total_items_price_in_cart(self):
         return(sum([price
                 for price, quantity in self.items.values()]))

sc = ShoppingCart()
sc.add('book', 30, 1)
sc.add('toothbrush', 4, 10)
print(sc.total_items_in_cart())
print(sc.total_items_price_in_cart())

3 个答案:

答案 0 :(得分:1)

将您的acks=all retries=0 batch.size=1MB buffer.memory=101*1024*1024 linger.ms=1000 key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer compression.type=lz4 request.timeout.ms=90000 props.put(ProducerConfig.METADATA_FETCH_TIMEOUT_CONFIG, 90000); props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 90000 功能更改为:

1)2018-05-29 09:19:40.919 ERROR 134700 --- [ad | producer-1] o.s.k.support.LoggingProducerListener    : Exception thrown when sending a message with key='null' and payload=' 
org.apache.kafka.common.errors.TimeoutException: Expiring 2 record(s) for demoTopicxyz-0 due to 30012 ms has passed since last append

输出有问题的输入数据:

  

total_items_price_in_cart

答案 1 :(得分:1)

我只想定义一个新的实例变量,例如_total_price,并在添加项目时保持更新:

class ShoppingCart(object):
    def __init__(self):
        self.item = None
        self.quantity = None
        self.price = None
        self.items = {}
        self._total_price = 0

    def add(self, item, price, quantity):
        if item in self.items:
            previous_quantity = self.items[item]['quantity']
            previous_price = self.items[item]['price']
            self.items[item] = {'quantity': previous_quantity + quantity,
                                'price': previous_price + price}
        else:
            self.items[item] = {'quantity':quantity, 'price':price}
        self._total_price += price * quantity

    @property
    def total_items_in_cart(self):
        return len(self.items) # better return a value instead of printing it

    @property
    def total_items_price_in_cart(self):
        return self._total_price

sc = ShoppingCart()
sc.add('book', 30, 1)
# sc.add('book', 132, 1)

sc.add('toothbrush', 4, 10)
# sc.add('toothbrush', 5, 20)

print(sc.total_items_in_cart)
print(sc.total_items_price_in_cart)

当然,当用户想要从购物车中删除商品时,您需要处理此案例。

答案 2 :(得分:0)

您的ShoppingCart班级有价格属性,但您不使用它。 您应该只使用self.items = {},不要使用self.itemself.quantityself.price

但是,对于你的问题,解决方案是:

print(cart_price_total) # this does not print what I want...

是的但看起来你的cart_price_total没有质疑你的物品价值......但是价值和物品数量都计算在内。

试试这个:

print(sum([sc.items[x]['price']*sc.items[x]['quantity'] for x in sc.items]))