直接上代码:
#定义节点
class Node:
def __init__(self,father,value,key):
self.father=father
self.value=value
self.key=key
#定义树结构
class Tree:
def __init__(self):
self.treeType=[dict,list]
self.nodes=[]
#通过list创建树,递归返回树的各节点
def paseNodes(self,tlist,fatherNode):
for item in tlist:
newNode = None
if type(tlist) is self.treeType[0]:
newNode=Node(fatherNode, tlist[item], item)
self.nodes.append(newNode)
elif type(tlist) is self.treeType[1]:
newNode=Node(fatherNode,item,None)
self.nodes.append(newNode)
if type(newNode.value) in self.treeType:
self.paseNodes(newNode.value,newNode)
return self.nodes
#打印树节点的key="src"的所有值,来个复杂点的字典
b={"name":123,"data":{"result":[{"src":"python1"},{"src":"python2"},{"name":123,"data":{"result":[{"src":"python1"},{"src":"python2"},{"src":"python3"}]}},{"name":123,"data":{"result":[{"src":"python1"},{"src":"python2"},{"src":"python3"}]}},{"src":"python3"}]}}
tree=Tree().paseNodes(b,id(b))
for node in tree:
if node.key is "src":
print(node.value)