假设我们有一个带边的列表,我们使用图形创建了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
重复。如何创建图表以获得边缘权重?
答案 0 :(得分: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)
链接列表受宠若惊,以获取顶点列表。并不是顶点不能重复,因此不需要显式删除它们中的重复元素。
您可以通过指定relative keyword参数(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
输出是这样的:
modelList
有关详细信息,请参阅igraph:igraph.Graph,igraph.Vertex和igraph.Edge
的文档答案 1 :(得分:0)
我有一个代码,用于查找边缘以查看它是否已存在于图形中。所以,它是这样的:
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']