python中字典的循环
我有以下脚本:python中字典的循环,python,dictionary,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, 1
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
每一行由店铺id、数量、价格组成,我想循环该店铺的金额,以便为每个店铺id提供:
total_price = qty * price
示例:我的店铺id为1,3,在店铺中_id=1 我有两个订单行[OrderLine1,2,30,OrderLine1,1,50] 我想计算具有相同店铺id的所有订单行的总价,其中:总价=数量*价格
提前感谢您可以使用下面的代码片段填充词典商店。if语句检查字典shop_sum中是否已经存在shop_id,并将其初始化为零。if后的逻辑执行实际总和。您可以使用列表理解来更优雅地编写此代码,您可能需要仔细阅读
请澄清。你是说你想要一本字典,它的键是ID,值是总价?还是别的什么?请给出一个你想要得到的确切输出的具体例子。我有车间id 1,3,在车间id=1中我有两个订单行,我想计算所有具有相同车间id的订单行的总价,其中:总价=数量*价格谢谢,但这不计算价格我更新了我的问题,请检查一下
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