Python 从类别列表创建递归列表
我正在编写一系列代码,其中我有一些以下格式的输入数据:Python 从类别列表创建递归列表,python,list,algorithm,dictionary,recursion,Python,List,Algorithm,Dictionary,Recursion,我正在编写一系列代码,其中我有一些以下格式的输入数据: _input = [ ('Cat 1', 'Sub Cat 1', 'lvl_3_cat-1'), ('Cat 1', 'Sub Cat 2', 'lvl_3_cat-2'), ('Cat 2', 'Sub Cat 3', 'lvl_3_cat-3') ] 我需要将下面的catefories列表转换成一个父子嵌套列表,可以通过迭代来获得嵌套关系列表 预期产量 本例中的输入具有3级嵌
_input = [
('Cat 1', 'Sub Cat 1', 'lvl_3_cat-1'),
('Cat 1', 'Sub Cat 2', 'lvl_3_cat-2'),
('Cat 2', 'Sub Cat 3', 'lvl_3_cat-3')
]
我需要将下面的catefories列表转换成一个父子嵌套列表,可以通过迭代来获得嵌套关系列表
预期产量
本例中的输入具有3级嵌套,但这可以是动态的,即高达n级
我当前的代码
我的电流输出
可以使用基于的树状数据结构。这将使用类别级别作为关键帧,使用子树作为值:
from collections import defaultdict
def tree():
return defaultdict(tree)
def insert(node, value):
if value:
key, *remainder = value
insert(node[key], remainder)
data = [
('Cat 1', 'Sub Cat 1', 'lvl_3_cat-1'),
('Cat 1', 'Sub Cat 2', 'lvl_3_cat-2'),
('Cat 2', 'Sub Cat 3', 'lvl_3_cat-3'),
]
root = tree()
for sample in data:
insert(root, sample)
import json
print(json.dumps(root, indent=2, default=dict))
这将产生以下数据结构:
{
第1类:{
子类别1:{
第3级第1类:{}
},
次级类别2:{
第3级第2类:{}
}
},
第2类:{
次级类别3:{
第三级第三类:{}
}
}
}
如果您确实希望保留带有名称和子键的单独dict包装器,可以使用以下函数转换上述树:
def convert(node):
return [{'name': key, 'children': convert(value)} for key, value in node.items()]
from pprint import pprint
pprint(convert(root))
其输出为:
[{'children':[{'children':[{'children':[],'name':'lvl_3_cat-1'}],
“名称”:“子类别1”},
{'children':[{'children':[],'name':'lvl_3_cat-2'}],
'名称':'子类别2'}],
'名称':'类别1'},
{'children':[{'children':[{'children':[],'name':'lvl_3_cat-3'}],
'名称':'子类别3'}],
“名称”:“第2类”}]
这个简单的一行怎么样。这对于任何深度都是递归的-
from pprint import pprint
f = lambda x: {'name':x[0], 'children': f(x[1:])} if len(x)>0 else {}
output = [f(i) for i in _input]
pprint.pprint(output, sort_dicts=False)
如果您可以避免每个子级中的listdict,只需握住一个dict,那么它看起来更干净,与@a_guest输出相同
from pprint import pprint
f = lambda x: {x[0]:f(x[1:])} if len(x)>0 else {}
output = [f(i) for i in _input]
pprint(output, sort_dicts=False)
预期的输出会是什么样子?@Lohith用预期的O更新了问题/p@Mohan,如果您感兴趣,我已经添加了一个没有导入集合的版本。效果很好!!谢谢
def convert(node):
return [{'name': key, 'children': convert(value)} for key, value in node.items()]
from pprint import pprint
pprint(convert(root))
from pprint import pprint
f = lambda x: {'name':x[0], 'children': f(x[1:])} if len(x)>0 else {}
output = [f(i) for i in _input]
pprint.pprint(output, sort_dicts=False)
[{'name': 'Cat 1',
'children': {'name': 'Sub Cat 1',
'children': {'name': 'lvl_3_cat-1', 'children': {}}}},
{'name': 'Cat 1',
'children': {'name': 'Sub Cat 2',
'children': {'name': 'lvl_3_cat-2', 'children': {}}}},
{'name': 'Cat 2',
'children': {'name': 'Sub Cat 3',
'children': {'name': 'lvl_3_cat-3', 'children': {}}}}]
from pprint import pprint
f = lambda x: {x[0]:f(x[1:])} if len(x)>0 else {}
output = [f(i) for i in _input]
pprint(output, sort_dicts=False)
[{'Cat 1': {'Sub Cat 1': {'lvl_3_cat-1': {}}}},
{'Cat 1': {'Sub Cat 2': {'lvl_3_cat-2': {}}}},
{'Cat 2': {'Sub Cat 3': {'lvl_3_cat-3': {}}}}]