Introduction

Tips

  • import package

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

     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

  • Node with the largest degree

     >>> max(G.degree, key=lambda x: x[1])
    ('H', 4)
  • Nodes in descending order of degree

     for tup in sorted(G.degree, key=lambda x: x[1], reverse=True):
      print(tup)
  • the number of connected components

     >>> nx.number_connected_components(G)
    3
  • print the set of nodes for each connected component

     for iset in nx.connected_components(G):
      print(iset)
    {'B', 'A'}
    {'E', 'C', 'D'}
    {'L', 'I', 'M', 'J', 'G', 'H', 'K', 'F'}
This article is from qbit snap

qbit
268 声望279 粉丝