【发布时间】:2018-12-12 21:38:22
【问题描述】:
例如:
d = dict()
#Map "Parent" to a list of "children" values
d["Parent"] = []
d["Parent"].append("Child1")
d["Parent"].append("Child2")
d["Parent"].append("Child3")
#I know the following is wrong, but I want each list that "Parent" maps to, also to map to a list- how would I do this?
d["Parent"]["Child3"] = []
d["Parent"]["Child3"].append("GrandChild1")
这基本上看起来像一棵树(不是二元树),其中有一个顶级父级,指向其子级(可能超过 2 个),每个子级都可以指向其多个子级。还有其他方法吗?
【问题讨论】:
-
是的,您只需要一个字典而不是针对每个键存储的列表。但是你打算走多远?很快我认为它会变得笨拙
-
d["Child3"].append("GrandChild1")如果你只是想建立映射 -
假设它最多有 5 个深度级别
-
但是 d["Child3"].append("GrandChild1") 没有建立映射,因为它没有显示“Parent”到“Child3”到“GrandChild1”的层次结构(其中看起来像 d["Parent"]["Child3"].append("GrandChild1"),但这是不正确的。
-
它基本上是一个树实现,其中一个节点指向它的子节点,但我不知道如何用字典和列表来实现它。
标签: python dictionary data-structures tree