有時候graph建好后,我們並不清除該graph內節點的,邊的信息,這就需要調用函數去查看了.
目錄:
注意:如果代碼出現找不庫,請返回第一個教程,把庫文件導入.
6.查看Graph的信息
6.1查看graph內節點,邊的數量
- #生成graph
- G=nx.path_graph(8)
- nx.draw(G,with_labels=True)
- plt.axis('on')
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #查看節點和邊的情況
- print('number of nodes',G.number_of_nodes())
- print('number of edges',G.number_of_edges())

例子圖
輸出:
- number of nodes 8
- number of edges 7
6.2查看graph中的點,邊
- #輸出graph所有的點和邊
- print('all nodes of Graph',G.nodes())
- print('all edges of Graph',G.edges())
輸出:
- all nodes of Graph [0, 1, 2, 3, 4, 5, 6, 7]
- all edges of Graph [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
6.3查看某些節點的度
- #查看節點2和3的度
- print('degree of some nodes',G.degree([2, 3]))
輸出:
- degree of some nodes [(2, 2), (3, 2)]
6.4查看節點&邊信息
- #設置一些節點信息
- G.nodes[1]['room'] = 714
- G.nodes[1]['color'] = 'b'
- #設置一些邊信息
- G[1][2]['weight'] = 4.7
- G[1][2]['color'] = "blue"
- print('imformation of one nodes',G.nodes[1])
- print('imformation of all nodes',G.nodes.data())
- print('imformation of all nodes',G.edges.data()) #邊不支持[x]這樣的下標訪問
輸出:
- imformation of one nodes {'room': 714, 'color': 'b'}
- imformation of all nodes [(0, {}), (1, {'room': 714, 'color': 'b'}), (2, {}), (3, {}), (4, {}), (5, {}), (6, {}), (7, {})]
- 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遍歷一個有權圖
- #定義一個有權無向圖
- FG = nx.Graph()
- FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
- #遍歷鄰接矩陣
- for n, nbrs in FG.adj.items():
- for nbr, eattr in nbrs.items():
- wt = eattr['weight']
- #權重小於0.5的輸出
- if wt < 0.5:
- print('way1-(%d, %d, %.3f)' % (n, nbr, wt))
- #遍歷所有邊
- for (u, v, wt) in FG.edges.data('weight'):
- #權重小於0.5的輸出
- if wt < 0.5:
- print('way2-(%d, %d, %.3f)' % (u, v, wt))
輸出:
- way1-(1, 2, 0.125)
- way1-(2, 1, 0.125)
- way1-(3, 4, 0.375)
- way1-(4, 3, 0.375)
- way2-(1, 2, 0.125)
- way2-(3, 4, 0.375)