Python 基于值和属性检索图的顶点
我正在使用python中的networkx创建具有顶点和边的图形Python 基于值和属性检索图的顶点,python,networkx,Python,Networkx,我正在使用python中的networkx创建具有顶点和边的图形 G=add_edge(vertex1,vertex2) vertex1和vertex2是整数,即 G=add_edge(4,3), G=add_edge(2,3) etc.. 因为,在python中,如果我们只给出边列表,它将创建顶点并在指定顶点之间创建边 现在,我需要向图的顶点添加一个属性,也就是说,我希望基本上根据属性将顶点分成若干组 因此,我能做到 G.node[your_vertex]['attribute'] = v
G=add_edge(vertex1,vertex2)
vertex1
和vertex2
是整数,即
G=add_edge(4,3),
G=add_edge(2,3)
etc..
因为,在python中,如果我们只给出边列表,它将创建顶点并在指定顶点之间创建边
现在,我需要向图的顶点添加一个属性,也就是说,我希望基本上根据属性将顶点分成若干组
因此,我能做到
G.node[your_vertex]['attribute'] = value
将属性添加到已创建的图形G
由于可以有许多不同的属性和不同的值,如何检索顶点
您可以在节点上循环,查看哪些节点:
如果你需要做很多这些查找,这可能不是很快-你可能想考虑建立一些你感兴趣的属性/值的节点索引,假设节点的属性/值不会经常改变。
>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_edge(4, 3)
>>> G.add_edge(2, 3)
>>> G.add_edge(2, 5)
>>> G.node[2]['foo'] = 'bar'
>>> G.node[3]['foo'] = 'qux'
>>> attribute = 'foo' # the attribute you want
>>> value = 'bar' # the value you want for that attribute
>>> [n for n in G.node if attribute in G.node[n].keys()]
[2, 3]
>>> [n for n in G.node if G.node[n].get(attribute) == value]
[2]