Wxpython:TreeCtrl:对树进行迭代

Sum*_*sht 4 python wxpython

我正在使用以下方法迭代 wxpython treectrl 的所有节点。

 def get_desired_parent(self, name, selectednode = None):
    if selectednode == None:
        selectednode = self.treeCtrl.RootItem
    # First perform the action on the first object separately
    childcount = self.treeCtrl.GetChildrenCount(selectednode, False)
    if childcount == 0:
        return None

    (item,cookie) = self.treeCtrl.GetFirstChild(selectednode)
    if self.treeCtrl.GetItemText(item) == name:
        return item

    while childcount > 1:
        childcount = childcount - 1
     # Then iterate over the rest of objects
        (item,cookie) = self.treeCtrl.GetNextChild(item,cookie)
        if self.treeCtrl.GetItemText(item) == name:
            return item
    return None
Run Code Online (Sandbox Code Playgroud)

当我在结构内部递归迭代时,多余代码的问题变得更加明显。是否有另一种以更紧凑的方式执行相同操作的方法,以使我的代码更简洁/pythonic。

jad*_*k94 5

您可以使用此函数内部(仅在其命名空间中)的函数来检查它是否与条件匹配。如果它确实返回了该项目,如果它没有返回,请继续。

否则,您可以在该while行之后检查您的状况。这样,item变量将由循环之前的第一个子项定义,并像其他任何项一样进行评估。

还有一种方式:(或两者的混合)

(child, cookie) = self.GetFirstChild(item)
while child.IsOk():
    do_something(child)
     (child, cookie) = self.GetNextChild(item, cookie)
Run Code Online (Sandbox Code Playgroud)