# python之networkx库小结

import networkx as nx
G=nx.Graph()#创建空的简单图
G=nx.DiGraph()#创建空的简单有向图
G=nx.MultiGraph()#创建空的多图
G=nx.MultiDiGraph()#创建空的有向多图

G.add_node(1)#加1这个点



G.remove_node()
G.remove_nodes_from()
G.remove_edge()
G.remove_edges_from()
G.clear()

G.add_nodes_from([1,2,3])
for n in G.nodes():
print(n)
for e in G.edges():
print(e)
print(G.degree())


1
2
3
(1, 2)
(1, 3)
[(1, 2), (2, 1), (3, 1)]#1这个点有两条边连着，2、3只有一条边连着

k_5=nx.complete_graph(5)#完全图
k_3_3=nx.complete_bipartite_graph(3,3)#完全二分图

from matplotlib import pyplot as plt
import networkx as nx
G=nx.Graph()
nx.draw_networkx(G)
plt.show()

1、无权无向图最短路径

from matplotlib import pyplot as plt
import networkx as nx
G=nx.path_graph(5)
path=nx.single_source_shortest_path(G,2)
length=nx.single_source_shortest_path_length(G,2)
print(path)
print(length)
nx.draw_networkx(G)
plt.show()

{2: [2], 1: [2, 1], 3: [2, 3], 0: [2, 1, 0], 4: [2, 3, 4]}
{2: 0, 1: 1, 3: 1, 0: 2, 4: 2}

2、有权无向图

from matplotlib import pyplot as plt
import networkx as nx
nodes=[0,1,2,3,4]
edges=[(0,1,10),(0,3,30),(0,4,100),(1,2,50),(2,3,20),(2,4,10),(3,4,60)]
G=nx.Graph()
path=nx.single_source_dijkstra_path(G,4)
length=nx.single_source_dijkstra_path_length(G,4)
print(path)
print(length)
nx.draw_networkx(G)
plt.show()

{4: [4], 0: [4, 2, 3, 0], 2: [4, 2], 3: [4, 2, 3], 1: [4, 2, 1]}
{4: 0, 2: 10, 3: 30, 1: 60, 0: 60}

01-16 1016
03-03
11-14 1万+
07-31 592
02-22 2万+
12-09 1232
03-07 623
06-18 2万+
04-17 2万+
01-06 2705
10-13 8158
03-05 4225