请问python如何把字符串和有权树互换?
请问我有这样的字符串 [[A:10, B:8, C:7]D:11, E:12, F:13], 我还有个node类, ABCDEF都是node类的对象,我要建立一棵树,R代表根,R有三个子节点DEF, D又有三个子节点ABC, 有没有好的例子可以学习一下阿
如果我建立了这样的一棵树 要如何便利这颗树 也请教有没有这方面的例子 学习一下 谢谢!
[解决办法]
treestr = "[[A:10, B:8, C:7]D:11, E:12, F:13]"MyTree = {}def createTree(substring,node): l = len(substring) if l == 0: return if substring[0] == '[': c = 1 i = 1 while c != 0 and i < l: if substring[i] == '[': c += 1 elif substring[i] == ']': c -= 1 else : pass i += 1 j = i while j < l: if substring[j] == ',': break j += 1 if j < l: #1:i,i:':',':':j key = substring[i:j].split(':')[0] value = substring[i:j].split(':')[1] subtreestring = substring[1:i-1] #need to treat space........ node[key] = {} node[key]['value'] = value node[key]['subkey'] = {} createTree(subtreestring,node[key]['subkey']) createTree(substring[j+1:],node) return d = substring.split(',') node[d[0].split(':')[0]] = {} node[d[0].split(':')[0]]['value']= d[0].split(':')[1] node[d[0].split(':')[0]]['subtree']= {} createTree(','.join(d[1:]),node)if __name__ == '__main__': createTree(treestr[1:-1],MyTree) print MyTree