2016-09-13 28 views
0

我有一个数据库表,其中每一行有:成本/数量汇总在树形结构 - Python的

name, 
child1, 
child1_quantity, 
child2, 
child2_quantity, 
child3, 
child3_quantity, 
price 

这个表将被带入Python作为字典或词典的词典列表(没有按”问题)。它会是这个样子:

[{name: A, child1: C1, child1_quantity:2, child2:C2, child2_quantity: 1, child3: C3, child3_quantity:3, price: null}, 
{name: C1, child1: C1A, child1_quantity:5, child2: C1B, child2_quantity:2, child3: C1C, child3_quantity:6, price: 3}, 
{name: C2, child1: C2A, child1_quantity:5, child2: C2B, child2_quantity:2, child3: C2C, child3_quantity:10, price: 4}, 
{name: C3, child1: C3A, child1_quantity:3, child2: C3B, child2_quantity:7, child3: C3C, child3_quantity:15, price: null}] 

问题案例: 我希望能够进入组件的名称和获得它的价格。如果价格在表格中给出,很容易,请将其退回。 如果没有给出一个价格,我们不得不通过增加它的价格来计算价格的孩子 即

(child1 price x child1 qty) + (child2 price x child2 qty) + ..... 

但每个孩子可以/不可以价格。因此,我们需要从孩子那里找到孩子的总成本,然后把它提出来.....直到我们得到孩子的总价,然后总结他们以得到我们的价格感兴趣的部分。这是一个递归类型的问题,我认为,但我想不出如何概念化或表示数据以使我的目标成为可能。我可以得到一些线索/指针吗? sql递归查询不是一个选项。我试图在python数据结构或对象中执行此操作。谢谢。

回答

1
def find_price(self, name): 
    if self.dictionary[name]["price"]: 
     return self.dictionary[name]["price"] 
    else: 
     #assuming this is in a class...otherwise use global instead of self 
     return self.find_price(dictionary[name]["child1"])*dictionary[name]["child1_quantity"] + find_price(self.dictionary[name]["child2"])*self.dictionary[name]["child2_quantity"]#.....etc 

这也假设您读取数据的顶级对象是一个名称也用作键名称的字典。

+0

如果您觉得这回答了问题,也请接受答案。 –