【问题标题】:Setting default property value in graph_tool在 graph_tool 中设置默认属性值
【发布时间】:2016-03-22 11:33:47
【问题描述】:

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

# 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

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

【问题讨论】:

    标签: python graph-tool


    【解决方案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)
    

    【讨论】:

    • 感谢您的回答。我是 graph_tool 的新手,现在我意识到我忽略了 new_vertex_property 的签名......我的错误。
    猜你喜欢
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2012-04-07
    • 2011-09-16
    • 2011-03-21
    相关资源
    最近更新 更多