2016-09-13 34 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

如果您覺得這回答了問題,也請接受答案。 –