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))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章