简体   繁体   English

在 Python 中使用图形工具添加许多顶点属性

[英]Adding many vertex properties with graph-tool in Python

I have several features to add to each vertex in my graph.我有几个功能要添加到我的图中的每个顶点。 The way I know of adding vertex properties to a graph is the following:我知道将顶点属性添加到图形的方法如下:

g = Graph()
g.set_directed(False)

vprop_feature_name = g.new_vertex_property("int")
g.vp.feature_name = vprop_feature_name

Then you could associate data to the vertices by然后你可以通过以下方式将数据关联到顶点

for data in feature:
    v = g.add_vertex()
    g.vp.feature_name[v] = data

However, if I had many features, it would be quite laborious to manually code new variables vprop_feature_name for each feature.但是,如果我有很多特征,手动为每个特征编写新变量vprop_feature_name将非常费力。 How could I automatically add features without manually creating new variable names?如何在不手动创建新变量名的情况下自动添加功能?

There is no need to store each property in its own local variable.无需将每个属性存储在其自己的局部变量中。 Just use the dict-like access for properties to assign each property under its own name.只需使用类似 dict 的属性访问权限,即可将每个属性分配到自己的名称下。

Here's an example.这是一个例子。

import graph_tool.all as gt

# Example graph
g = gt.Graph(directed=False)
g.add_vertex(10)
g.add_edge_list(list(zip(range(0,9), range(1,10))))

# Create some vertex properties
feature_names = ['foo', 'bar', 'baz', 'wonka', 'wookie']
for name in feature_names:
    g.vertex_properties[name] = g.new_vertex_property("int")

# You can use either dict-like access or attribute-like access.
g.vertex_properties['foo'][0] = 123
g.vp.foo[9] = 789

print(g.vp.foo.get_array().tolist())
[123, 0, 0, 0, 0, 0, 0, 0, 0, 789]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM