2017-10-31 15 views
1

このjavascriptの例をPythonに移植したいと思います。ここでノードの子孫を取得するPymongoツリー構造

は、すべてのノードの子孫を取得元の例である:

var descendants=[] 
var stack=[]; 
var item = db.categoriesPCO.findOne({_id:"Cell_Phones_and_Accessories"}); 
stack.push(item); 
while (stack.length>0){ 
    var currentnode = stack.pop(); 
    var children = db.categoriesPCO.find({parent:currentnode._id}); 
    while(true === children.hasNext()) { 
     var child = children.next(); 
     descendants.push(child._id); 
     stack.push(child); 
    } 
} 


descendants.join(",") 
//Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 

Pythonのバージョンは、これに似ています:

def descendants(): 
    descendants = [] 
    stack = [] 

    item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"}) 

    stack.append(item) 

    while(len(stack) > 0): 
     currentNode = stack.pop() 

     children = db.electronics.find({'parent': currentNode["_id"] }) 

     while(next(children, None)): 
      child = next(children, None) 
      descendants.append(child['_id']) 
      stack.append(child) 

    print(descendants) 

しかし、あなたは子孫の一部である出力から参照してくださいねなど行方不明

[ '電池'、 'C​​ell_Phones_and_Smartphones'、 'サムスン'、 'HTC']

答えて

1

最初次の()を使用して、項目をスキップ作っているので、あなたは、whileループ内で二回次呼んでいます、上記のコードの修正がある

def descendants(): 
    descendants = [] 
    stack = [] 

    item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"}) 

    stack.append(item) 

    while(len(stack) > 0): 
     currentNode = stack.pop() 

     children = db.electronics.find({'parent': currentNode["_id"] }) 

     for child in children: 
      descendants.append(child['_id']) 
      stack.append(child) 

    print(descendants) 

を次のコードを試していますが、データベースには、次のコード

def descendants(): 
    descendants = [] 
    stack = [] 

    item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"}) 

    stack.append(item['_id']) 

    while stack: 

     children = db.electronics.find({'parent': {'$in':stack}}) 
     stack = [] 
     for child in children: 
      descendants.append(child['_id']) 
      stack.append(child['_id']) 

    print(descendants) 
から呼び出しを減らすことができます
関連する問題