我在图表中有一个图表g
和一个节点列表subset_nodes
。我想删除v_i
中v_j
,v_i
节点v_j
和subset_nodes
之间的所有边缘。
我目前正在使用以下方法:
import igraph
g = igraph.Graph.Full(10)
subset_nodes = [g.vs[i] for i in range(4)]
to_delete = set()
for node in subset_nodes:
for v in node.neighbors():
if v in subset_nodes:
tp = (node.index, v.index)
to_delete.add( tuple(sorted(tp)) )
print(len(g.es))
g.delete_edges( to_delete )
print(len(g.es))
打印:
45
39
这是有道理的,因为
10 choose 2 = 45 # total # of edges (since it is a full graph)
4 choose 2 = 6 # # of removed edges
45 - 6 = 39 # # of edges remaining
我的问题是,是否有更好,更优雅或更加pythonic的做法?
答案 0 :(得分:1)
Igraph有" induced_subgraph"方法可以方便一个更简洁的解决方案:
import igraph as ig
g=ig.Graph.Full(10)
subset_nodes=[g.vs[i] for i in range(4)]
smallgraph=g.induced_subgraph(subset_nodes)
es=ig.EdgeSeq(smallgraph)
mytup=[e.tuple for e in es]
g.delete_edges(mytup)
答案 1 :(得分:1)
另一种解决方案是:
from igraph import Graph
g = Graph.Full(10)
g.es.select(_within=range(4)).delete()