循环在python中的字典

时间:2015-11-20 14:46:24

标签: python dictionary

我有以下脚本:

from collections import defaultdict

class OrderLine:
   def __init__(self, shop_id, qty, price):
    self.shop_id = shop_id
    self.qty = qty
    self.price = price

order_lines = [OrderLine(1, 2, 30), OrderLine(1, 1, 50), OrderLine(3, 3, 10)]
shop_sum = defaultdict(int)
for order_line in order_lines:
   print order_line.price
   print order_line.qty
   print order_line.shop_id

每一行都包含(shop_id,qty,price)我想为这个shop_sum循环给我每个shop_id:

total_price = qty * price

示例:我在shop_id = 1中有商店ID(1,3) 我有两个订单行[OrderLine(1,2,30),OrderLine(1,1,50)] 我想计算所有具有相同shop_id的订单行的总价格,其中:total_price = qty * price

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以使用下面的代码段填充字典shop_sumif语句检查字典shop_id中是否已存在shop_sum并将其初始化为零。 if执行实际总和之后的逻辑。您可以使用列表推导更优雅地编写此代码,您可能需要阅读this

from collections import defaultdict

class OrderLine:
   def __init__(self, shop_id, qty, price):
    self.shop_id = shop_id
    self.qty = qty
    self.price = price

order_lines = [OrderLine(1, 2, 30), OrderLine(1, 1, 50), OrderLine(3, 3, 10)]
shop_sum = defaultdict(int)
for order_line in order_lines:
   shop_id =  order_line.shop_id  
   if shop_id not in shop_sum:
       shop_sum[shop_id]=0
   shop_sum[shop_id]  = shop_sum[shop_id] + order_line.qty * order_line.price
   print order_line.price
   print order_line.qty
   print order_line.shop_id