假设它的行为良好(没有循环,没有重复的名称或一个孩子有多个父母),您可以简单地使用“有向图”并遍历它。为了找到根,我还使用了一个包含布尔值的字典,该布尔值指示该名称是否存在任何父项:
lst = [('john','marry'), ('mike','john'), ('mike','hellen'), ('john','elisa')]# Build a directed graph and a list of all names that have no parentgraph = {name: set() for tup in lst for name in tup}has_parent = {name: False for tup in lst for name in tup}for parent, child in lst: graph[parent].add(child) has_parent[child] = True# All names that have absolutely no parent:roots = [name for name, parents in has_parent.items() if not parents]# traversal of the graph (doesn't care about duplicates and cycles)def traverse(hierarchy, graph, names): for name in names: hierarchy[name] = traverse({}, graph, graph[name]) return hierarchytraverse({}, graph, roots)# {'mike': {'hellen': {}, 'john': {'elisa': {}, 'marry': {}}}}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)