我想列出如下列表:
groups = ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]
并将其转换为嵌套列表,可能采用以下格式,但我愿意接受建议:
groups_sorted = [{
"name":"foo",
"children": [
{
"name": "foo::fone",
"children": [ ... ]
}, ...
]
}, ...
]
以便使用层次结构拆分对列表进行排序::
。我需要每个children
键本身都是列表,因为列表的原始顺序很重要。
我已经玩了几个小时,并且能够从单个顶部节点开始创建一个递归字典,但我做不到最后一点。在下面找到我的工作:
def children_of(node, candidates):
children = []
remainder = []
for c in candidates:
sub = node + "::"
if c.startswith(sub):
try:
c[len(sub):].index("::") # any more separators = not a child
remainder.append(c)
except ValueError: # a child
children.append(c)
else: #not related
remainder.append(c)
return children, remainder
def sortit(l):
if l:
el = l.pop(0)
children, remainder = children_of(el,l)
if children:
return { "name": el,
"children": [sortit([c]+remainder) for c in children]
}
else:
return { "name": el }
编辑:@Thijs van Dien 的解决方案非常好,但我需要 2.6 兼容性,这阻止了我使用 OrderDicts。