引子

Tips

  • 导入包

    import networkx as nx               # 载入networkx包
    import matplotlib.pyplot as plt     # 用于画图
    G = nx.Graph()                      # 无向图
  • 连通分量

    edges = [('A', 'B'), ('C', 'E'), ('D', 'E'),
           ('F', 'G'), ('F', 'H'), ('G', 'I'),
           ('G', 'J'), ('H', 'J'), ('H', 'L'),
           ('H', 'M'), ('I', 'K'), ('J', 'K'),
           ('L', 'K'), ('L', 'H'), ('L', 'M')]
    G.add_edges_from(edges)
    nx.draw_networkx(G)
    plt.show()

    Figure_1.png

  • 度最大的节点

    >>> max(G.degree, key=lambda x: x[1])
    ('H', 4)
  • 节点按度降序

    for tup in sorted(G.degree, key=lambda x: x[1], reverse=True):
      print(tup)
  • 连通分量的个数

    >>> nx.number_connected_components(G)
    3
  • 打印各连通分量的节点集合

    for iset in nx.connected_components(G):
      print(iset)
    {'B', 'A'}
    {'E', 'C', 'D'}
    {'L', 'I', 'M', 'J', 'G', 'H', 'K', 'F'}
本文出自 qbit snap

qbit
268 声望279 粉丝