So we'll break this down into two observations. First we can access all the edges out of a node (and the associated data) with G.edges(node, data = True)
. Second, there are ways to efficiently loop through these edges just counting those with positive sign. More generally, this approach can be used to count the number of edges out of a node that have any particular property.
import networkx as nx
G = nx.DiGraph()
G.add_edge(0,2,sign=-1)
G.add_edge(0,1, sign = 1)
G.add_edge(2,3,sign = 1)
G.add_edge(3,0, sign=-1)
print(G.edges(0, data=True))
>[(0, 2, {'sign': -1}), (0, 1, {'sign': 1})]
Note that the edge (3,0) did not appear here. So G.edges(0, data=True)
results in the edges that start from 0
and includes the data you've attached to the edge. (in your final code, obviously you don't actually want this print statement).
Now we'll use that in a generator and sum up the number of elements.
s = sum(1 for (u,v,d) in G.edges(0, data=True) if d['sign']==1)
print(s)
> 1
What I've done is create a generator that goes through all edges out of 0
and if the sign is 1
, it adds 1 to the output.
If that last sentence doesn't make sense, look at this answer: https://stackoverflow.com/a/7223557/2966723 to given an idea of what is going on, and for more about generators, start with Understanding generators in Python.