根据值和属性检索图形的顶点

时间:2014-10-30 00:04:38

标签: python networkx

我正在使用python中的networkx创建一个包含顶点和边的图。

G=add_edge(vertex1,vertex2)

vertex1vertex2是整数,即

G=add_edge(4,3),
G=add_edge(2,3)
etc..

因为在python中,如果我们只给出边列表,它会创建顶点并在指定的顶点之间创建边。

现在我需要在图形的顶点添加一个属性,即我希望基本上根据属性将顶点分成几组。

因此,我可以做到

G.node[your_vertex]['attribute'] = value

将属性添加到已创建的图形G

由于可以有许多不同的属性和不同的值,我如何检索顶点

  1. 按其价值
  2. 按其属性

1 个答案:

答案 0 :(得分:1)

您可以循环遍历节点并查看哪些节点:

  1. 对属性有一些价值(即属性是属性字典中的一个键);或者,
  2. 具有您对属性所需的特定值。
  3. >>> 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]
    

    如果你需要做很多这些查找,这可能不会很快 - 你可能想要考虑构建某种具有你感兴趣的属性/值的节点索引,假设一个节点是属性/值不会经常变化。