[英]Python. Graph tree recursive from database
I have a table "Node" with fields "id" and "name", also I have a table "Link" that links Node among themselves as many-to-many. 我有一个带有字段“ id”和“ name”的表“ Node”,还有一个表“ Link”,该表将Node之间的链接链接为多对多。
Node id | name 1 node1 2 node2 3 node3 4 node4 5 node5 6 node4 7 node5 Link id | node_id | node2_id 1 1 2 2 2 3 3 3 5 4 2 4 5 3 6 6 3 7 node4 node7 | | node1-->node2-->node3-->node6 | node5
How do I use python to generate this graph, list or dict with nested. 如何使用python生成带有嵌套的图,列表或字典。 I have a problem with the construction of the algorithm.
我对算法的构造有疑问。 I have function get_derrived with returned a list of derived elements.
我有函数get_derrived与返回派生元素的列表。 My code is:
我的代码是:
c.tree = {}
def get_tree(node_id):
for node in get_derrived(node_id):
if not node in c.tree:
c.tree[node] = {}
get_tree(node.id)
get_tree(id)
In sum I have for node1: 总而言之,我对于node1:
c.tree = {node1: {}, node2: {}, node3:{}, node4: {}, node5: {}, node6: {}, node7: {}} c.tree = {节点1:{},节点2:{},节点3:{},节点4:{},节点5:{},节点6:{},节点7:{}}
for node2: 对于node2:
c.tree = {node2: {}, node4: {}, node3: {}, node5: {}, node6: {}, node7: {}} c.tree = {节点2:{},节点4:{},节点3:{},节点5:{},节点6:{},节点7:{}}
But I need dict {node2: {node4: {}, node3: {node7: {}, node5: {}, node6: {} }}}. 但是我需要字典{node2:{node4:{},node3:{node7:{},node5:{},node6:{}}}}。
Please have look at this example from the python-graph. 请从python-graph看这个例子 。
It shows how to programmatically create a grah and how to display it using graphviz (it should be already installed in your system if you're using any Linux distribution). 它显示了如何以编程方式创建grah以及如何使用graphviz显示它(如果您使用的是任何Linux发行版,则应已将其安装在系统中)。
Use dot and graphviz. 使用点和graphviz。
There are libraries to help generate the dot code, but you can easily write your own to dump out the text into a file. 有一些库可以帮助生成点代码,但是您可以轻松编写自己的库以将文本转储到文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.