print G.number_of_nodes()
8
print G.number_of_edges()
3
1
2
3
4
What to use as nodes and edges
你可能已经注意到在NetworkX中节点和边并没有被指定一个对象,因此你就可以自由地指定节点和边的对象。最常见的对象是数值和字符串,但是一个节点可以是任意hash对象(除了None对象),一条边也可以关联任意的对象x,比如:
G.add_edge(a,b,object=x)。
举个关于边关联对象的例子,加入a和b是两个人,而他们两个人之间的联系(边),可以是一个概率,即边的对象是一个概率值,表示这两个人之间每天通电话的可能性。
可以看到这是十分强大而且有用的,但是如果你滥用该方法将会导致意想不到的后果,除非你对Python真的很熟悉。如果你不是很确定,你可以考虑使用conver_node_label_to_integers(),他可以将一个图的所有节点按顺序转化为整数对象赋给另一个图。
Accessing edges and neighbors
除了上面提到的那些访问节点和边的方法以外( eg:Graph.nodes(), Graph.edges(), Graph.neighbors()…),也可以利用下标表示来获取边和邻居结点。
Class views provide basic reporting of nodes, neighbors, edges and degree. These views provide iteration over the properties as well as membership queries and data attribute lookup. The views refer to the graph data structure so changes to the graph are reflected in the views. This is analogous to dictionary views in Python 3. If you want to change the graph while iterating you will need to use e.g. for e in list(G.edges):. The views provide set-like operations, e.g. union and intersection, as well as dict-like lookup and iteration of the data attributes using G.edges[u, v][‘color’] and for e, datadict in G.edges.items():. Methods G.edges.items() and G.edges.values() are familiar from python dicts. In addition G.edges.data() provides specific attribute iteration e.g. for e, e_color in G.edges.data(‘color’):.
The basic graph relationship of an edge can be obtained in two ways. One can look for neighbors of a node or one can look for edges. We jokingly refer to people who focus on nodes/neighbors as node-centric and people who focus on edges as edge-centric. The designers of NetworkX tend to be node-centric and view edges as a relationship between nodes. You can see this by our choice of lookup notation like G providing neighbors (adjacency) while edge lookup is G.edges[u, v]. Most data structures for sparse graphs are essentially adjacency lists and so fit this perspective. In the end, of course, it doesn’t really matter which way you examine the graph. G.edges removes duplicate representations of undirected edges while neighbor reporting across all nodes will naturally report both directions.
Any properties that are more complicated than edges, neighbors and degree are provided by functions. For example nx.triangles(G, n) gives the number of triangles which include node n as a vertex. These functions are grouped in the code and documentation under the term algorithms.