networkx笔记

初始化及清空

import networkx as nx
G = nx.Graph() # 创建无向图
G = nx.DiGraph() # 创建有向图
G = nx.MultiGraph() # 创建多重无向图
G = nx.MultiDigraph() # 创建多重有向图
G.clear() #清空图

加入边或节点

G.add_edge('a', 'b') # 'a'和'b'是顶点的名称,可以是int值也可以是string
G.add_edges_from([('a', 'b')]) # 可以从列表批量添加
G.add_cycle(['f','g','h','j'])         #加环
H = nx.path_graph(10)          # 返回由10个节点挨个连接的无向图,参数可以是数字也可以是列表
G.add_nodes_from(H)            # 创建一个子图H加入G
G.add_node(H)                  # 直接将图作为节点
nx.path_graph:
"""Returns the Path graph `P_n` of linearly connected nodes.

    Parameters
    ----------
    n : int or iterable
        If an integer, node labels are 0 to n with center 0.
        If an iterable of nodes, the center is the first.
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.

"""

删除边或节点

G.remove_node('a')    # 删除指定节点
G.remove_nodes_from(['b','c','d','e'])    #删除list中的节点

获取图的基本信息

d = G.degree('a') # 获取'a'的度
d_some = G.degree([0, 1, 2]) # 可以传入列表,得到的是 [(0, 1), (1, 2), (2, 2)],注意这个不是list,需要用list函数转换一下
d_all = G.degree() # 如果不传入参数,默认得到的是全部顶点的度,格式和上一步相同
node_nums =G.number_of_nodes() # 获取节点的数目
nodes = G.nodes() # 获取所有的节点
edge_nums = G.size() # 获取无向图边的数目
edges = G.edges() # 获取所有的边
neighbors_a = G.neighbors('a') # 获取'a'的所有相邻顶点
# 遍历边
for u,v,d in G.edges(data = 'weight'):
        print((u,v,d))
# 通过邻接矩阵遍历边
for n, nbrs in G.adjacency():
	for nbr, eattr in nbrs.items():
		print(n, nbr, eattr)
adjacency:
"""Returns an iterator over (node, adjacency dict) tuples for all nodes.

For directed graphs, only outgoing neighbors/adjacencies are included.

Returns
-------
adj_iter : iterator
   An iterator over (node, adjacency dictionary) for all nodes in
   the graph.

Examples
--------
>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

"""

获取最大联通子图

largest_components=max(nx.connected_components(G),key=len) # 返回一个顶点的set
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值