你看过吗this精彩的文章?要真正理解 Python 中的模式,这是必不可少的阅读内容。您的问题可以被认为是一个图形问题 - 查找关系基本上就是查找从子节点到父节点的所有路径。
由于可能存在任意数量的嵌套(child->parent1->parent2...),因此您需要一个递归解决方案来查找所有路径。在你的代码中,你有 2for
循环 - 正如您发现的那样,最多只会产生 3 级路径。
下面的代码改编自上面的链接以解决您的问题。功能find_all_paths
需要一个图表作为输入。
让我们从您的文件创建图表:
graph = {} # Graph is a dictionary to hold our child-parent relationships.
with open('testing.csv','r') as f:
for row in f:
child, parent = row.split(',')
graph.setdefault(parent, []).append(child)
print graph
对于您的示例,应该打印:
{'C': ['A', 'B'], 'B': ['A'], 'D': ['B', 'C']}
以下代码直接来自论文:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
for path in find_all_paths(graph, 'D', 'A'):
print '|'.join(path)
Output:
D|B|A
D|C|A
D|C|B|A