gpt4 book ai didi

python - 计算networkx中仅包含具有特定属性的边的节点的度

转载 作者:行者123 更新时间:2023-12-01 04:43:18 25 4
gpt4 key购买 nike

图中的所有边都有一个属性,即“颜色”。我想要图中节点的度数,但只计算 '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("colour 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})

关于python - 计算networkx中仅包含具有特定属性的边的节点的度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30077957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com