`````
import xml.etree.ElementTree as ET
test = """
<expression>
<plus>
<int value="5"/>
<int value="10"/>
<times>
<int value="3"/>
<minus>
<int value="4"/>
<plus>
<int value="-1000"/>
<int value="999"/>
</plus>
</minus>
</times>
</plus>
</expression>
"""
data = []
keys = ['minus','plus','times']
xmlTree = ET.fromstring(test)
for ele in xmlTree.iter():
if ele.tag in keys:
data.append(ele.tag)
elif 'value' in ele.attrib:
data.append(int(ele.attrib.get('value')))
# data = ['plus', 5, 10, 'times', 3, 'minus', 4, 'plus', -1000, 999]
calc = {'plus': lambda x, y: x+y, 'minus': lambda x, y: x-y, 'times': lambda x, y: x * y}
def calc_data(lst):
stack = []
for item in lst:
if item not in calc:
stack.append(item)
else:
while len(stack) > 1:
a, b = stack.pop(), stack.pop()
res = calc[item](a, b)
stack.append(res)
return stack[0]
print(calc_data(data[::-1]))
```````
在楼上的基础上测试了一下,感谢 @
necomancer