前言
我们再 html 端json 以及 mongodb 存储的时候 ,经常会遇到 json的嵌套树状结构,但是在 python 处理数据时 ,list 有很方便,两者的转换通常是难以避免的
而且,很多时候,我们需要把一个 list 数据嵌入到一个 树状结构中去。
所以实现了,这个把 list 作为一条路径嵌入 dict 中的方法
数组结构与树状结构
数组结构 = [ [中国,河南,鹤壁] ,
[中国,河南,郑州] ,
[中国,北京,朝阳] ,
]
树状结构 = { 中国 :{ 河南 :{ 鹤壁,郑州 } , 北京 :{ 朝阳 } } }
python 实现
将一个数组元素添加到,树状结构中
# 把一个 路径集合 变成一个 树状字典
# list 转 dict
class MyTree:
def __init__(self):
self.tree={}
# onepoint 是 list
def append_Point_to_tree(self, onepoint):
nowPositon = self.tree
index = 0
while index < len(onepoint):
if nowPositon.__contains__(onepoint[index]):
nowPositon = nowPositon[onepoint[index]]
index += 1
else:
#创建新节点
nowPositon[onepoint[index]] = {}
return self.tree
# 把【 【路径1 a,b,c,d】 ,【路径2】 】
# 多条路径一次性插入到树中
def insert_list_to_tree(self, pointlist):
for onepoint in pointlist:
self.append_Point_to_tree(onepoint)
如何把一棵树还原成一个list
# 树状字典转 路由 list
# 遍历树
def traverse_tree(onedict):
data_list=[]
start_list=list(onedict.keys())
deep_list =[0 for item in start_list]
temp_dict={}
now_deep=0
now_dict=onedict
while start_list!=[]:
one_key=start_list.pop()
now_deep=deep_list.pop()
if now_dict[one_key]!={}:
now_dict = now_dict[one_key]
temp_dict[now_deep]=one_key
for one_key2 in now_dict:
start_list.append(one_key2)
deep_list.append(now_deep+1)
else:
temp_dict[now_deep]=one_key
# one_key = start_list.pop()
data_list.append(list(temp_dict.values()))
if deep_list==[]:
break
now_deep = deep_list[-1]
# print(temp_dict)
# print(one_key)
# print(now_deep)
now_dict=onedict
for i in range(now_deep):
now_dict = now_dict[temp_dict[i]]
# now_dict=now_dict[one_key]
# time.sleep(1)
return data_list
# for item in data_list:
# print(item)
# print(len(data_list))