python - python-igraph如何添加带有权重的边?
问题描述
python-igraph如何添加带有权重的边?
我有一个像[('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), ('1', '86', 2.0), ('10', '100', 38.0)]
. 元组中的最后一个是边从'1'
到的权重'177'
。但是怎么添加呢?我用
g.add_vertices(vertexList)
g.add_edges(edgelist)
但这是错误的。
解决方案
We need to do some pre-processing first.
The following code works fine and does what you asked.
from igraph import *
# Here we have 5 edges
a = [('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0),
('1', '86', 2.0), ('10', '100', 38.0)]
edge = []
weights = []
# the loop for i is in range(5) because you have 5 edges
for i in range(5):
for j in range(2):
k =2
edge.append(a[i][j])
weights.append(a[i][k])
edges = [(i,j) for i,j in zip(edge[::2], edge[1::2])]
list1 = []
for i in range(len(edges)):
list1.append((int(edges[i][0]), int(edges[i][1])))
g= Graph()
g.add_vertices(178)
g.add_edges(list1)
g.es['weight'] = weights
g.ecount()
5
g.es['weight']
[1.0, 1.0, 2.0, 2.0, 38.0]
推荐阅读
- swift - 解析时为文本提供属性的原始字符串命令?
- tensorflow2.0 - 非法指令。加载 libtensorflow_cc.so 时 nsync::nsync_mu_init(nsync::nsync_mu_s_*) 中的 0x00007ffff3712210
- python - Numpy 精确值
- azure-active-directory - Spring Boot 与 Azure AD BC 的集成
- google-analytics - Google Analytics 4 和 Measurement Protocol API
- sql - 如何从一个表中为另一个表的每一行选择行并将它们解析为 JSON
- npm - 努力在 NPM 上的 Bootstrap 4 上使用 datetimepicker
- azure-devops - 如何将双引号字符串列表作为天蓝色管道变量输入传递给 terraform 任务?
- java - 有没有办法将一个数组放入另一个数组中,其元素由 2 个其他元素分隔?
- javascript - Populate Jquery Autocomplete With Google Contacts