gpt4 book ai didi

python - Wxpython:TreeCtrl:迭代树

转载 作者:行者123 更新时间:2023-11-28 17:50:51 24 4
gpt4 key购买 nike

我正在使用以下方法遍历 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

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

最佳答案

您可以使用此函数内部(仅在其 namespace 中)的函数来检查它是否与条件匹配。如果它没有返回项目,则继续。

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

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

(child, cookie) = self.GetFirstChild(item)
while child.IsOk():
do_something(child)
(child, cookie) = self.GetNextChild(item, cookie)

关于python - Wxpython:TreeCtrl:迭代树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10205221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com