如何使这样的方法,
#!/usr/bin/python
tree = { 0:(None, [1,2,3]),
1:(0, [4]),
2:(0, []),
3:(0, [5,6]),
4:(1, [7]),
5:(3, []),
6:(3, []),
7:(4, []),
}
def find_children(tree, id):
print "node:", id, tree[id]
for child in tree[id][1]:
find_children(tree, child)
if __name__=="__main__":
import sys
find_children(tree, int(sys.argv[1]))
$ ./tree.py 3
node: 3 (0, [5, 6])
node: 5 (3, [])
node: 6 (3, [])
值得注意的是,python有一个相当低的默认递归限制,1000我认为。
如果你的树实际上变得很深,你会很快达到目的。 可以杀青这个了,
sys.setrecursionlimit(100000)
,并检查它,
sys.getrecursionlimit()
我是在想,这将返回是一个给定项目的后代项目的大名单,从正确的级别,但是你会失去数据集的结构? – notreadbyhumans 2009-08-07 21:57:56
所以,这与这个单行列表理解相同:“def getChildren(item): return [getChildren(child)for child in allItems if child.parent == item]” 我从来没有见过列表理解递归之前。 – hughdbrown 2009-08-07 22:53:32