python - 如何从这个列表中获取所有的孩子、孙子……?
问题描述
我items
是亲子关系。每个孩子都知道它的父母,但父母不知道它的孩子和孙子:
items = [
{'id': 1, 'parent': None},
{'id': 2, 'parent': 1},
{'id': 3, 'parent': 2},
{'id': 4, 'parent': None},
{'id': 5, 'parent': 4},
]
我正在尝试构建一个 dict,其中包含所有项目 id 及其所有子项、孙子项等的列表:
all_children_of_items = {
1: [2, 3], # 2 = child, 3 = grandchild
2: [3],
3: [],
4: [5],
5: [6]
}
我目前的方法只考虑孩子,而不是孙子:
all_children_of_items = {}
while True:
change = False
for item in items:
if item['id'] not in all_children_of_items:
all_children_of_items[item['id']] = []
if item['parent']:
if item['parent'] not in all_children_of_items:
all_children_of_items[item['parent']] = []
if item['id'] not in all_children_of_items[item['parent']]:
all_children_of_items[item['parent']].append(item['id'])
if not change:
break
当前结果:
{
1: [2],
2: [3],
3: [],
4: [5],
5: []
}
任何的想法?提前致谢!
解决方案
你可以试试这个:
tree = {}
for item in items:
parent = item['id']
child = [it['id'] for it in items if it['parent'] == parent]
grandchild = [it['id'] for c in child for it in items if it['parent'] == c]
tree[parent] = [*child, *grandchild]
print(tree)
输出:
{1: [2, 3], 2: [3], 3: [], 4: [5], 5: []}
我看不到小时候5
的6
情况,所以我的代码也没有。
可以进一步优化代码,并针对更一般的用例进行修改。我把它留给你,你认为合适。
编辑:
为了:
items = [{'id': 1, 'parent': None},
{'id': 2, 'parent': 1},
{'id': 3, 'parent': 2},
{'id': 4, 'parent': 3},
{'id': 5, 'parent': 4}]
代码:
def nepotism(parent):
lineage = []
def recurs(parent):
for item in items:
if item['parent'] == parent:
possible_parent = item['id']
lineage.append(possible_parent)
recurs(possible_parent)
recurs(parent)
return lineage
tree = dict([(item['id'], nepotism(item['id'])) for item in items])
print(tree)
输出:
{1: [2, 3, 4, 5], 2: [3, 4, 5], 3: [4, 5], 4: [5], 5: []}
推荐阅读
- c# - 如何将图像添加到将随机显示的文本
- php - 为什么在发出 post 请求时用户名不会出现在我的有效负载中?
- algorithm - 在线性时间内找到未排序数组中的加权中位数
- java - 如何正确调整视图的大小,使其底部以编程方式与 ConstraintLayout 中其他视图的顶部对齐?
- swift - 未维护 ViewController 参考
- python - 在 JSON 文件中更新 Python 中的键值
- python - 仅检查 OpenCV 中视频源的特定部分
- c# - 在 C# 中为特定进程实例获取私有工作集内存的最佳方法
- sharepoint - 将 Sharepoint 环境从一个场复制到另一个场
- asp.net-mvc - 如何在 asp.net core 2.2 pages 站点上路由到 wwwroot/index.html