wushaogui

有时候graph建好后,我们并不清除该graph内节点的,边的信息,这就需要调用函数去查看了.

目录:


注意:如果代码出现找不库,请返回第一个教程,把库文件导入.

6.查看Graph的信息

6.1查看graph内节点,边的数量

  1. #生成graph 
  2. G=nx.path_graph(8) 
  3. nx.draw(G,with_labels=True) 
  4. plt.axis(\'on\') 
  5. plt.xticks([]) 
  6. plt.yticks([]) 
  7. plt.show() 
  8.  
  9. #查看节点和边的情况 
  10. print(\'number of nodes\',G.number_of_nodes()) 
  11. print(\'number of edges\',G.number_of_edges()) 

enter description here
例子图

输出:

  1. number of nodes 8 
  2. number of edges 7 

6.2查看graph中的点,边

  1. #输出graph所有的点和边 
  2. print(\'all nodes of Graph\',G.nodes()) 
  3. print(\'all edges of Graph\',G.edges()) 

输出:

  1. all nodes of Graph [0, 1, 2, 3, 4, 5, 6, 7] 
  2. all edges of Graph [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)] 

6.3查看某些节点的度

  1. #查看节点2和3的度 
  2. print(\'degree of some nodes\',G.degree([2, 3])) 

输出:

  1. degree of some nodes [(2, 2), (3, 2)] 

6.4查看节点&边信息

  1. #设置一些节点信息 
  2. G.nodes[1][\'room\'] = 714 
  3. G.nodes[1][\'color\'] = \'b\' 
  4. #设置一些边信息 
  5. G[1][2][\'weight\'] = 4.7 
  6. G[1][2][\'color\'] = "blue" 
  7.  
  8. print(\'imformation of one nodes\',G.nodes[1]) 
  9. print(\'imformation of all nodes\',G.nodes.data()) 
  10.  
  11. print(\'imformation of all nodes\',G.edges.data()) #边不支持[x]这样的下标访问 

输出:

  1. imformation of one nodes {\'room\': 714, \'color\': \'b\'} 
  2. imformation of all nodes [(0, {}), (1, {\'room\': 714, \'color\': \'b\'}), (2, {}), (3, {}), (4, {}), (5, {}), (6, {}), (7, {})] 
  3. imformation of all nodes [(0, 1, {}), (1, 2, {\'weight\': 4.7, \'color\': \'blue\'}), (2, 3, {}), (3, 4, {}), (4, 5, {}), (5, 6, {}), (6, 

7, {})]

6.5遍历一个有权图

  1. #定义一个有权无向图 
  2. FG = nx.Graph() 
  3. FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) 
  4.  
  5. #遍历邻接矩阵 
  6. for n, nbrs in FG.adj.items(): 
  7. for nbr, eattr in nbrs.items(): 
  8. wt = eattr[\'weight\'] 
  9. #权重小于0.5的输出 
  10. if wt < 0.5:  
  11. print(\'way1-(%d, %d, %.3f)\' % (n, nbr, wt)) 
  12.  
  13. #遍历所有边 
  14. for (u, v, wt) in FG.edges.data(\'weight\'): 
  15. #权重小于0.5的输出 
  16. if wt < 0.5:  
  17. print(\'way2-(%d, %d, %.3f)\' % (u, v, wt)) 

输出:

  1. way1-(1, 2, 0.125) 
  2. way1-(2, 1, 0.125) 
  3. way1-(3, 4, 0.375) 
  4. way1-(4, 3, 0.375) 
  5. way2-(1, 2, 0.125) 
  6. way2-(3, 4, 0.375) 

分类:

技术点:

相关文章: