假设我有一个复杂的树型字典列表组合:
dct = {'node': {'a':[1,2,3],
'b':{'b1':[{'b11':[4,5]},{'b12':[6,7]}],
'b2':[8,9]
},
'c':{'c1':[10,11],
'c2':[12,13]
}
}
}
我有更深层次的结构,我怎样才能以dict或其他形式获得每一组根到叶子路径。
例如路径:
{'node':'a','a':1}
{'node':'a','a':2}
{'node':'a','a':3}
{'node':'b','b':'b1','b1':'b11','b11':5}
{'node':'b','b':'b1','b1':'b11','b11':4}
{'node':'b','b':'b2','b2':9}
同样,我想要所有的路径!
发布于 2018-09-06 15:53:28
你可以使用yield
:
def get_paths(d, current=[]):
yield current
for a, b in d.items():
if not isinstance(b, list):
yield from get_paths(b, current+[a])
else:
for c in b:
if not isinstance(c, dict):
yield current+[a, c]
else:
yield from [current+[a]+i for i in get_paths(c)]
d = list(get_paths(dct))
new_d = [{b[i]:b[i+1] for i in range(len(b)-1)} for b in d if len(b) > 1]
输出:
[{'node': 'a', 'a': 1}, {'node': 'a', 'a': 2}, {'node': 'a', 'a': 3}, {'node': 'b'}, {'node': 'b', 'b': 'b1'}, {'node': 'b', 'b': 'b1', 'b1': 'b11', 'b11': 4}, {'node': 'b', 'b': 'b1', 'b1': 'b11', 'b11': 5}, {'node': 'b', 'b': 'b1'}, {'node': 'b', 'b': 'b1', 'b1': 'b12', 'b12': 6}, {'node': 'b', 'b': 'b1', 'b1': 'b12', 'b12': 7}, {'node': 'b', 'b': 'b2', 'b2': 8}, {'node': 'b', 'b': 'b2', 'b2': 9}, {'node': 'c'}, {'node': 'c', 'c': 'c1', 'c1': 10}, {'node': 'c', 'c': 'c1', 'c1': 11}, {'node': 'c', 'c': 'c2', 'c2': 12}, {'node': 'c', 'c': 'c2', 'c2': 13}]
https://stackoverflow.com/questions/-100002571
复制相似问题