set - python networkx remove nodes and edges with some condition -


in python library networkx remove nodes , edges of graph have property. example, suppose wanted remove nodes , edges degree of node < 2. consider following psuedocode:

vdict = g.degree_dict()         #dictionary of nodes , degrees g.remove_from_nodes(v in g s.t. vdict[v] < 2) 

i have seen syntax uses set theory notation still new python not know how use it. how convert working python code?

the graph.remove_nodes_from() method takes list (container actually) of nodes. need create list satisfies condition. can use python's list comprehension structure compactly create list of nodes delete.

in [1]: import networkx nx  in [2]: g = nx.graph()  in [3]: g.add_edge(1,2)  in [4]: g.add_edge(1,3)  in [5]: g.add_edge(1,4)  in [6]: g.add_edge(2,3)  in [7]: g.add_edge(2,4)  in [8]: g.degree() out[8]: {1: 3, 2: 3, 3: 2, 4: 2}  in [9]: remove = [node node,degree in g.degree().items() if degree > 2]  in [10]: remove out[10]: [1, 2]  in [11]: g.nodes() out[11]: [1, 2, 3, 4]  in [12]: g.remove_nodes_from(remove)  in [13]: g.nodes() out[13]: [3, 4] 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -