Python 计算仅包括networkx中具有特定属性的边的节点的阶数
我的图形中的所有边都有一个属性,比如“颜色”。我想要图中节点的度数,但只计算“color”=“red”的边Python 计算仅包括networkx中具有特定属性的边的节点的阶数,python,networkx,Python,Networkx,我的图形中的所有边都有一个属性,比如“颜色”。我想要图中节点的度数,但只计算“color”=“red”的边 G.add_edges_from([(1,2),(3,4),(4,5)], color='red') G.add_edges_from([(1,3),(1,4),(2,3)], color='blue') 所以我想G.degree(“color of edge=red”)给出{1:1,2:1,3:1,4:2,5:1}我找不到内置的方法,但您可以使用列表理解,通过测试属性值来构建一个新的图
G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
所以我想
G.degree(“color of edge=red”)
给出{1:1,2:1,3:1,4:2,5:1}
我找不到内置的方法,但您可以使用列表理解,通过测试属性值来构建一个新的图,(代码片段属性为):
对于这种情况,这里有一种不复制图形的方法。相反,它创建了一个新函数来计算度
In [1]: import networkx as nx
In [2]: from collections import defaultdict
In [3]: G = nx.Graph()
In [4]: G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
In [5]: G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
In [6]: def colored_degree(G, color):
degree = defaultdict(int)
for u,v in ((u,v) for u,v,d in G.edges(data=True) if d['color']==color):
degree[u]+=1
degree[v]+=1
return degree
...:
In [7]: colored_degree(G, 'red')
Out[7]: defaultdict(<type 'int'>, {1: 1, 2: 1, 3: 1, 4: 2, 5: 1})
In [8]: colored_degree(G, 'blue')
Out[8]: defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 2, 4: 1})
[1]中的:将networkx导入为nx
在[2]中:从集合导入defaultdict
[3]中:G=nx.Graph()
在[4]:G.从([(1,2),(3,4),(4,5)],color='red'添加边
在[5]:G.从([(1,3),(1,4),(2,3)],color='blue'添加边
[6]中:定义着色度(G,颜色):
度=默认dict(int)
对于u,v in((u,v)对于u,v,d in G.边(数据=真),如果d['color']==color):
度[u]+=1
度[v]+=1
回归度
...:
[7]中:有色度(G,'红色')
Out[7]:defaultdict(,{1:1,2:1,3:1,4:2,5:1})
[8]中:有色度(G,'蓝色')
Out[8]:defaultdict(,{1:2,2:1,3:2,4:1})
相关:
In [1]: import networkx as nx
In [2]: from collections import defaultdict
In [3]: G = nx.Graph()
In [4]: G.add_edges_from([(1,2),(3,4),(4,5)], color='red')
In [5]: G.add_edges_from([(1,3),(1,4),(2,3)], color='blue')
In [6]: def colored_degree(G, color):
degree = defaultdict(int)
for u,v in ((u,v) for u,v,d in G.edges(data=True) if d['color']==color):
degree[u]+=1
degree[v]+=1
return degree
...:
In [7]: colored_degree(G, 'red')
Out[7]: defaultdict(<type 'int'>, {1: 1, 2: 1, 3: 1, 4: 2, 5: 1})
In [8]: colored_degree(G, 'blue')
Out[8]: defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 2, 4: 1})