我有以下处理XML文件的代码:
for el in root:
checkChild(rootDict, el)
for child in el:
checkChild(rootDict, el, child)
for grandchild in child:
checkChild(rootDict, el, child, grandchild)
for grandgrandchild in grandchild:
checkChild(rootDict, el, child, grandchild, grandgrandchild)
...
...
正如您所看到的,在每次迭代中,我都只使用一个额外的参数调用同一个函数。有没有一种方法可以避免编写这么多基本上做相同事情的嵌套for循环?你知道吗
任何帮助都将不胜感激。非常感谢。你知道吗
为了便于理解,假设根看起来像这样:
那就像一棵树。我们可以通过这棵树找到一些路径,例如
(root, child1)
。当您将这些路径提供给checkChild
时,这将导致调用checkChild(rootNode, child1)
。最终checkChild
将为树中的每个路径准确调用一次。因此,我们可以将树写为路径列表,如下所示:此列表中路径的顺序恰好与循环结构匹配。它被称为深度优先。(另一种排序顺序,宽度优先,将首先列出所有子节点,然后列出所有子节点,最后列出所有子节点。)
上面的列表与代码中的
stack
变量相同,只是stack
只存储它需要记住的最少数量的路径。你知道吗总之,
recurse
一个接一个地生成这些路径,最后一位代码调用checkChild
方法,就像您在问题中所做的那样。你知道吗无论您希望对文件和目录执行什么操作,都可以遍历它们。在python中,我知道的最简单的方法是:
在遍历时,可以将添加到组或执行其他操作
假设
root
来自ElemenTree解析,您可以创建一个包含每个节点的所有祖先列表的数据结构,然后cnd对此进行迭代以调用checkChild:相关问题 更多 >
编程相关推荐