networkx构建图

networkx

networkx是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法

import networkx as nx
import matplotlib.pyplot as plt
 
G = nx.random_graphs.barabasi_albert_graph(100, 1)   # 生成一个BA无向图
G = nx.MultiGraph()     # 有多重边无向图
G = nx.MultiDiGraph()   # 有多重边有向图
G = nx.Graph()          # 无多重边无向图
G = nx.DiGraph()          # 无多重边有向图
...
G.clear()  # 清空图
G = nx.DiGraph()        # 无多重边有向图
G.add_node(2)  # 添加一个节点
G.add_nodes_from([3, 4, 5, 6, 8, 9, 10, 11, 12])  # 添加多个节点
G.add_cycle([1, 2, 3, 4])  # 添加环
G.add_edge(1, 3)  # 添加一条边
G.add_edges_from([[3, 5], [3, 6], [6, 7]])  # 添加多条边
G.remove_node(8)  # 删除一个节点
G.remove_nodes_from([9, 10, 11, 12])  # 删除多个节点
G.remove_edges_from(edges) #删除多条边
G.in_edges(node) # [partent,node]
G.out_edges(node) # [node,children]
list([node]) # node的所有children
nx.shortest_path(G,source=node1,target=node2)[1:-1] # node1到node2的最短路径,不包含首尾
posted @ 2021-12-09 16:06  梦想家肾小球  阅读(307)  评论(0编辑  收藏  举报