Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

networkx best practice getting edge attribute value while iterating over edges

Given a list of edges (or a generator). What is the most readable way to identify edges with a certain attribute value? For example all edges with an 'edge_type' of 'foo'?

Currently, my code looks like this:

for edge in nx_graph.out_edges(my_node):
   edge_type = nx_graph[edge[0]][edge[1]]['edge_type']
   if edge_type == 'foo':
       ...

Due to the many brackets this is not very easy to read...

A slightly more readable approach:

for edge in G.edges_iter(data=True):
    if edge[2]['edge_type']=='foo':
        ...

Yet it is still not very clear (especially the [2] ). Also, I am not sure how to use it with out_edges()

like image 235
langlauf.io Avatar asked Nov 29 '25 11:11

langlauf.io


1 Answers

Here's an option

for edge in ((u,v,data) for u,v,data in G.edges_iter(data=True) if data['edge_type']=='foo'): 
    ...
like image 54
Joel Avatar answered Dec 01 '25 01:12

Joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!