您是否看过this篇精彩的论文?真正了解python模式是必读的.您的问题可以认为是图形问题-找到关系基本上就是找到从子节点到父节点的所有路径.
由于可能存在任意数量的嵌套(child-> parent1-> parent2 …),因此您需要递归解决方案来查找所有路径.在您的代码中,您有2个for循环-如您所知,最多只会导致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)
输出:
D|B|A
D|C|A
D|C|B|A