NetworkX系列教程(5)-查看graph的信息


有時候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) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM