我有一个xml树:
<root>
<expression>
<add>
<number>1</number>
<number>2</number>
<number>3</number>
</add>
</expression>
</root>
我的函数遍历树,添加子文本的int。 print语句的最终结果是我需要的结果,但是如何从addleafnodes函数返回它呢?
root = etree.XML(request.data['expression'])
results = 0
def addleafnodes(root, results):
for child in root:
if root.tag != "root" and root.tag != "expression":
results += int(child.text)
print(results)
addleafnodes(child, results)
newresults = addleafnodes(root, results)
答案 0 :(得分:1)
您将results
递归递归,然后递增,但不要将其返回“上”。如果results
是一个对象,而您只是传递了一个引用,则可以在对addleafnodes
进行根调用之后查看它。
以下内容将总和返回到递归:
from xml.etree.ElementTree import XML
expr = """<root>
<expression>
<add>
<number>1</number>
<number>2</number>
<number>3</number>
</add>
</expression>
</root>
"""
root = XML(expr)
def addleafnodes(root, results):
for child in root:
if root.tag != "root" and root.tag != "expression":
results += int(child.text)
results = addleafnodes(child, results)
return results
newresults = addleafnodes(root, 0)
print(newresults)
我认为这种功能性方法不错,但是您也可以从递归内部简单地更新全局变量(我已从此代码段中删除了results = 0
)。
请注意,我不确定代码是否会因较深的表达式结构(例如嵌套的添加等)而中断。
答案 1 :(得分:0)
您的问题被标记为lxml
。如果您确实在使用lxml,则可以使用sum()
xpath函数来简化...
from lxml import etree
expr = """<root>
<expression>
<add>
<number>1</number>
<number>2</number>
<number>3</number>
</add>
</expression>
</root>
"""
root = etree.fromstring(expr)
def addleafnodes(elem):
return int(elem.xpath("sum(.//add/number)"))
newresults = addleafnodes(root)
print(newresults)
打印输出...
6