python - 如何在 Python 中创建映射到列表的键字典,其中列表中的每个元素都指向其他列表?

标签 python dictionary data-structures tree

例如:

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/

相关文章:

python - 有没有办法在我使用 python-selenium 的同时在 heroku 上使用 chrome 驱动程序?

C++有效地创建具有单个条目不同的 map

algorithm - 增广区间树

python - 我可以使用 Xcode 3.2 进行 Django 和 Python 网络开发吗?

python - 用于透明地使用 Websocket 和 Comet 的高级 Python 库 "fallback"

Python 检查日期是否为 future 30 天

css - 带有叠加图像的图像映射不起作用 + JSFiddle

python - 如果与当前标记相同,则删除句子中的前一个标记 python

algorithm - 二叉树中的成本搜索操作?

objective-c - Cocoa 中的双向映射