在graph_tool中设置默认属性值

时间:2016-03-22 11:33:47

标签: python graph-tool

我需要计算图中每个顶点满足给定条件(例如“ACondition”)的次数。为此,我需要确保将vertex属性初始化为零,这是我明确做的。请参阅下面的代码。

# Instantiates the graph object and the vertex property. 
import graph_tool.all as gt
g1 = gt.Graph()
g1.vp.AProperty = g1.new_vertex_property("int32_t")

# Sets the vertex property to zero (prior to counting).
for v1 in g1.vertices():
    g1.vp.AProperty[v1] = 0

# Counts the number of times "ACondition" is satisfied for each vertex.
for v1 in g1.vertices():
    if(ACondition == True):
        g1.vp.AProperty[v1] += 1

有没有办法指定属性的默认值,以便我不需要显式设置其初始值(即上面的第二个代码块)?

1 个答案:

答案 0 :(得分:1)

new_vertex_property接受将用于初始化属性的单个值或序列:g1.new_vertex_property("int32_t", 0)

我不确定你为什么说“需要确保将顶点属性初始化为零”,因为如果你不提供默认值,它将被初始化为零:

>>> g = gt.Graph()
>>> g.add_vertex(10)
>>> g.new_vertex_property('int').a
PropertyArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)

如果属性是真值,则应使用bool代替。

您还可以使用sumget_array()来计算满意的属性。

import graph_tool.all as gt
g = gt.Graph()

# Initialize property foo with False value
g.vp['foo'] = g.new_vertex_property('bool')

# How many vertices satisfy property foo
sum(g.vp['foo'].a)