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))
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
要将 DataFrame 数据转换树状结构,你可以使用递归或循环来构建树的节点,并将节点链接起来。下面是一个示例,演示如何将 DataFrame 转换树状结构: ```python import pandas as pd # 创建一个示例 DataFrame data = {'id': [1, 2, 3, 4, 5, 6], 'name': ['root', 'child1', 'child2', 'grandchild1', 'grandchild2', 'grandchild3'], 'parent_id': [None, 1, 1, 2, 2, 3]} df = pd.DataFrame(data) # 创建树节点类 class TreeNode: def __init__(self, id, name): self.id = id self.name = name self.children = [] # 创建树函数 def create_tree(df, parent_id=None): tree = [] for index, row in df.iterrows(): if row['parent_id'] == parent_id: node = TreeNode(row['id'], row['name']) children = create_tree(df, parent_id=row['id']) node.children.extend(children) tree.append(node) return tree # 将 DataFrame 转换为树 tree = create_tree(df) # 打印树结构 def print_tree(node, level=0): indent = ' ' * level print(f'{indent}id: {node.id}, name: {node.name}') for child in node.children: print_tree(child, level + 1) for node in tree: print_tree(node) ``` 在这个示例,首先定义了一个 TreeNode 类,用于表示树的节点。然后,创建了一个 create_tree 函数,用于递归地构建树结构。该函数根据 DataFrame 的 parent_id 列找到每个节点的子节点,并将它们链接到父节点的 children 列表。 最后,使用 print_tree 函数打印树结构。这个函数使用递归方式遍历树,并按层级缩进输出节点的 id 和 name 属性。 你可以根据实际情况修改代码,以适应你的 DataFrame 结构和数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yuemake999

请我喝茶呗

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

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

打赏作者

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

抵扣说明:

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

余额充值