例如:
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 = {}
d["Parent"] = {}
d["Parent"]["Child1"] = {}
d["Parent"]["Child2"] = {}
d["Parent"]["Child3"] = {}
d["Parent"]["Child3"]["GrandChild1"] = {}
d["Parent"]["Child3"]["GrandChild2"] = {}
但是,你要做什么?这可能不是使用 Python 执行此操作的最佳方法。 :-) 如果您可以让当前的代码正常工作,您可以将其发布到 https://codereview.stackexchange.com/然后。您将获得有关如何改进代码的宝贵反馈。
<小时/>顺便说一下,你可以用 dict.keys
查看“树”的“分支” :
print(d.keys())
print(d["Parent"].keys())
print(d["Parent"]["Child3"].keys())
哪个打印
dict_keys(['Parent'])
dict_keys(['Child3', 'Child2', 'Child1'])
dict_keys(['GrandChild2', 'GrandChild1'])
关于python - 如何在 Python 中创建映射到列表的键字典,其中列表中的每个元素都指向其他列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53751755/