python 中列表与树状结构的转换

前言

我们再 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))
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuemake999

请我喝茶呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值