【发布时间】:2014-02-06 12:44:30
【问题描述】:
我必须从树结构中提取节点,以便获得树中所有节点的平面列表。我想到了两个选择
干净、可读但可能效率不高,因为有很多列表合并:
def _recursive_extraction(node):
store = []
# .get_subnodes() returns only the direct children
for subnode in node.get_subnodes():
store.append(subnode)
subsubnodes = _recursive_extraction(subnode)
store += subsubnodes
return store
而且(可能)更有效,但可读性较差。我的老板试图说服我使用它,但我怀疑。它在一个可变对象内部传递,该对象被隐式/隐藏更新,在其他语言中作为“通过引用传递”。
def _recursive_extraction(node, store=None):
if store is None:
store = []
for subnode in node.get_subnodes():
store.append(subnode)
# Watch out! store is updated in this func call
_recursive_extraction(subnode, store)
return store
免责声明:代码未经测试,只是表达我的想法。
免责声明 2:“通过引用”是指传递可以更新的可变对象。
侧面编辑:将子节点批量附加到循环之外会更有效,如下所示:
def _recursive_extraction(node, store=None):
if store is None:
store = []
subnodes = node.get_subnodes()
store += subnodes
for subnode in subnodes:
# Watch out! store is updated in this func call
_recursive_extraction(subnode, store)
return store
【问题讨论】:
-
我会使用第二种形式,是的。所有 python 调用都是“通过引用传递”;该列表是一个可变引用。
-
我没有看到任何不使用第二个的理由。
-
好吧,看来Python的大师们都喜欢它:)
标签: python recursion pass-by-reference