创建图形时获取边权重

get edge weights when creating the graph

假设我们有一个带边的列表,并且我们用 igraph 创建了图:

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
g = ig.Graph()
for link in links:
    g.add_vertices(link)
g.add_edges(links)

print(g)
# IGRAPH UN-- 8 4 --
# + attr: name (v)
# + edges (vertex names):
# 2--1, 2--3, 1--2, 2--1

2 -- 1 重复。如何创建图形以获得边权重?

根据igraph文档,边可以重复,所以,如果你不想重复边,你需要自己删除它们。

这段代码展示了如何为边设置权重(或您想要的任何 属性)以及如何读取。

图表的创建

import igraph as ig

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
vertices = [v for s in links for v in s]  # = [1,2,1,3,2,4,1,2]
g = ig.Graph()
g.add_vertices(vertices)
for l in links:
  g.add_edge(l[0], l[1], weight=0.5*l[0]*l[1]) # weight value is just an example

print(g)

为了获得顶点列表,链接列表受宠若惊。并不是说顶点不能被复制,因此没有必要显式地删除其中的重复元素。

您可以通过指定相对关键字参数 (weight=0.5*l[0]*l[1]) 来指定要添加到边缘的任何 属性。

正在检索边信息

您只需 e['weight'] 即可检索权重,其中 e 是单边(igraph.Edge 对象)。在此示例中,它展示了如何遍历边集。

print("\nEdges\n")
for e in g.es():
  print("source: %s target: %d" % (e.source, e.target))
  print("multiplicity %d" % (g.count_multiple(e)))
  print("weight %f\n" % e['weight'])

输出是这样的:

Edges

source: 1 target: 2
multiplicity 2
weight 1.000000

source: 1 target: 3
multiplicity 1
weight 1.500000

source: 2 target: 4
multiplicity 1
weight 4.000000

source: 1 target: 2
multiplicity 2
weight 1.000000

更多细节请参考igraph的文档:igraph.Graph, igraph.Vertex and igraph.Edge

我有这方面的代码,用于查找边以查看它是否已存在于图中。所以,它是这样的:

edgelist = []
weights = []
for e in links:
    if e in edgelist:
        weights[edgelist.index(edge)] += 1
    else:
        edgelist.append(e)
        weights.append(1)

G = ig.Graph()
G.add_edges(edgelist)
G.es['weight'] = weights

编辑:当然,您可以使用 G.es['weight']

访问这些权重