networkx(三)

Graph—Undirected graphs with self loops

具有自循环的无向图

import networkx as nx
G = nx.Graph()#创建一个没有节点也没有边的空的无向图
G.add_node(1)#一次添加一个节点来生成无向图

你也可以从list dict set甚至是文件的一行以及把另一个图作为节点作为节点

G.add_nodes_from([2,3])
G.add_nodes_from(range(100,110))
G.nodes()
NodeView((1, 2, 3, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109))
H = nx.path_graph(10)
H
<networkx.classes.graph.Graph at 0x204f6b3f470>
G.add_nodes_from(H)
G.nodes()
NodeView((1, 2, 3, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 0, 4, 5, 6, 7, 8, 9))

除了字符串和整数外,任何可散列的Python对象(“None”除外)都可以表示一个节点,例如一个定制的节点对象,甚至另一个图

G.add_node(H)
G.add_edge(1,2)#你也可以通过边来生成无向图
G.add_edges_from([(1,2),(1,3)])#甚至是边的list
G.add_edges_from(H.edges)#以及是边的collection(我太菜,不知道把collection应该翻译成什么)

添加已连接的节点或者是边不会报错

每个图,节点和边都可以在关联的属性字典中保存键/值属性对(键值必须是可哈希的)

G = nx.Graph(day = "Friday")
G.graph
{'day': 'Friday'}
G.add_node(1,time='5pm')
G.add_nodes_from([3],time='2pm')
G.nodes[1]
{'time': '5pm'}
G.nodes[1]['room'] = 714 #节点必须是已经存在的才可以使用G.nodes
del G.nodes[1]['room']
list(G.nodes(data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]

边的处理也相同

G.add_edge(1,2,weight=4.7)
G.add_edges_from([(3,4),(4,5)],color='red')
G.add_edges_from([(1,2,{'color':'blue'}),(2,3,{'weight':8})])
G[1][2]['weight'] = 4.7
G.edges[1,2]['weight'] = 4

许多常见的图形功能允许python语法加快报告速度。

1 in G#检查节点是否在图中
True
[n for n in G if n < 3]#遍历节点
[1, 2]
len(G)#查看节点在图中的数目
5

遍历图形所有边缘的最佳方法通常是通过邻居。邻居被报告为邻接字典G.adj或G.adjacency()

for n,nbrsdict in G.adjacency():
    for nbr,eattr in nbrsdict.items():
        if 'weight' in eattr:
            pass

使用边的方法可能更方便

for u,v,weight in G.edges.data('weight'):
    if weight is not None:
        pass
发布了9 篇原创文章 · 获赞 0 · 访问量 437

猜你喜欢

转载自blog.csdn.net/zr1213159840/article/details/104203011