我想将这个javascript示例移植到Python。在
以下是获取所有节点后代的原始示例:
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版本与此类似:
^{pr2}$但是正如您从输出中看到的,一些子代丢失了。在
['Batteries', 'Cell_Phones_and_Smartphones', 'Samsung', 'HTC']
在while循环中调用next两次,因此第一个next()将使您跳过这些项,请尝试以下代码
以上是对您的代码的更正,但是您可以减少来自以下代码的数据库调用
^{pr2}$相关问题 更多 >
编程相关推荐