finding edges in networkx that meet a certain crit

2019-04-17 03:37发布

问题:

I have a networkx digraph with attributes on the nodes, and I want to find all edges where a particular node attribute is different. Is there a way to do this automatically, or do I have to iterate with edge_iter(data=True) and find them myself?

回答1:

There is no built-in function for this but it is pretty simple:

import networkx as nx

G = nx.Graph()
G.add_node(1,color='red')
G.add_node(2,color='red')
G.add_node(3,color='blue')
G.add_node(4,color='blue')

G.add_edges_from([(1,2),(1,3),(3,4)])

for (u,v) in G.edges_iter():
    if G.node[u]['color'] != G.node[v]['color']:
        print u,v