Ich versuche, ein ähnliches Problem wie die hier aufgeführt zu lösen: Python: Combinations of parent-child hierarchyPython Liste von Listen Rekursion fügt zusätzliche Verschachtelung
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')
gewünschte Ausgabe:
[['top', '1a', '2a', '3a'],
['top', '1a1'],
['top', '1b', '2b'],
['top', '1c', '2c', '3c', '4c']]
tatsächlicher Ausgang:
[[[['top', '1a', '2a', '3a']]],
['top', '1a1'],
[['top', '1b', '2b']],
[[[['top', '1c', '2c', '3c', '4c']]]]]
Irgendwelche Ratschläge, wie ich die zusätzliche Verschachtelung entfernen kann? Vielen Dank!
@ TigerhawkT3, die nicht das gleiche Problem ist! selbst wenn du modifizierst: 'test = find_all_paths (graph, 'top')' to 'test = find_all_paths (graph, 'top', [])' du wirst das gleiche Problem bekommen – alfasin
Das hat nichts mit dem zu tun Standardargument, da das Argument aufgrund der ersten Zuweisung nicht innerhalb der Grenzen der Funktion mutiert ist. Ich stimme dieser Frage erneut zu. – 2ps
Ja, ich werde es wieder öffnen. Ich denke, TigerhawkT3 war hier ein wenig rücksichtslos. – wim