假设它的乖巧(无周期,不重名或多个家长一个孩子),你可以简单地使用“有向图”并遍历它。为了找到根(S)我也使用含有一个布尔值,表示是否存在用于名称的任何父的字典:
lst = [('john','marry'), ('mike','john'), ('mike','hellen'), ('john','elisa')]
# Build a directed graph and a list of all names that have no parent
graph = {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 hierarchy
traverse({}, graph, roots)
# {'mike': {'hellen': {}, 'john': {'elisa': {}, 'marry': {}}}}
如果还有一个元素,说'('elisa','mike')',应该发生什么? – MSeifert
你到目前为止尝试过什么?你具体在哪里卡住? – CoryKramer
我相信这是错误的,因为迈克是约翰和海伦的父亲,约翰是艾丽莎的父亲,这意味着艾莉莎是迈克的孙子,不能是迈克的母亲。 –