我试图解决类似问题的一个这里列出:Python: Combinations of parent-child hierarchyPython列表增加了额外的嵌套
graph = {}
nodes = [
('top','1a'),
('top','1a1'),
('top','1b'),
('top','1c'),
('1a','2a'),
('1b','2b'),
('1c','2c'),
('2a','3a'),
('2c','3c'),
('3c','4c')
]
for parent,child in nodes:
graph.setdefault(parent,[]).append(child)
def find_all_paths(graph, start, path=[]):
path = path + [start]
if not graph.has_key(start):
return path
paths = []
for node in graph[start]:
paths.append(find_all_paths(graph, node, path))
return paths
test = find_all_paths(graph, 'top')
所需的输出:
[['top', '1a', '2a', '3a'],
['top', '1a1'],
['top', '1b', '2b'],
['top', '1c', '2c', '3c', '4c']]
实际输出:
[[[['top', '1a', '2a', '3a']]],
['top', '1a1'],
[['top', '1b', '2b']],
[[[['top', '1c', '2c', '3c', '4c']]]]]
有关如何删除额外嵌套的任何建议?谢谢!
@ TigerhawkT3这是不一样的问题!即使你将'test = find_all_paths(graph,'top')'修改为'test = find_all_paths(graph,'top',[])',你也会得到相同的问题 – alfasin
这与这个无关作为参数的默认参数在函数的范围内没有因第一次赋值而发生变化。我投票重新提出这个问题。 – 2ps
是的,我会重新打开它。我认为TigerhawkT3在这里有点鲁莽。 – wim