数据构造---家族树

1. 第一种(家族关系)

comment_list = [
	{"id": 1, "name": "a", "content": "xx", "pid":None},
	{"id": 2, "name": "a", "content": "xx", "pid":1},
	{"id": 3, "name": "a", "content": "xx", "pid":1},
	{"id": 4, "name": "a", "content": "xx", "pid":3},
]


comment_dict = {}

######### 家族树关系的构建 ############
# 1.循环初始数据 添加children 构造字典格式
for item in comment_list:
	item["children"] = []
	comment_dict[item["id"]] = item
	
	
# 2. 循环初数据 判断pid,如果有pid,添加到相应的父级
for row in comment_list:
	if not row["pid"]:
		continue
	pid = row["pid"]
	comment_dict[pid]["children"].append(row)
	
print(comment_dict)

2. 第二种(父子关系)

comment_list = [
	{"id": 1, "name": "a", "content": "1"},
	{"id": 2, "name": "a", "content": "2"},
	{"id": 3, "name": "a", "content": "3"},
	{"id": 4, "name": "a", "content": "4"},
]
son_list = [
	{"id": 1, "name": "a1", "content": "1-1", "replay_id": 1,"depth": 2, "root": 1},
	{"id": 2, "name": "a1", "content": "2-1", "replay_id": 2,"depth": 2, "root": 2},
	{"id": 3, "name": "a1", "content": "3-1", "replay_id": 3,"depth": 2, "root": 3},
	{"id": 4, "name": "a1", "content": "4-1", "replay_id": 4,"depth": 2, "root": 4},
	{"id": 5, "name": "a1", "content": "4-2", "replay_id": 4,"depth": 2, "root": 4},
]

comment_dict = {}

######### 二级评论的处理 ############
# 1.循环初始数据 添加children 构造初始化字典格式
for item in comment_list:
	item["children"] = []
	comment_dict[item["id"]] = item
	

	
# 2. 循环二级评论 用replay_id,去初始化的字典里面,找到对应的父级,添加到children里面
for row in son_list:
	replay_id = row["replay_id"]
    if replay_id in son_list:
	    comment_dict[replay_id]["children"].append(row)
	
print(comment_dict)
print(comment_dict.values())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

骑猪去兜风z1

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值