簡體   English   中英

在for循環中從圖中刪除節點

[英]delete nodes from a graph in for loop

我正在使用igraph-python 我正在嘗試解決一個稱為最長誘導路徑的問題,我在開始時選擇一個隨機節點,找到它的鄰居,然后根據接近中心性的值從鄰居中選擇一個,刪除其他節點等等我的代碼如下

from random import randint
import networkx as nx
import numpy as np
from igraph import *
from numpy import random
def maximum(a, n):
maxpos = a.index ( max ( a ) )
return maxpos

G = Graph ()
G.add_vertices(5)
G.add_edges([(0, 1), (0, 2),(1,3),(2,3),(3,4)])

n = G.vcount()
first = random.randint(n)
neigh = G.neighbors(first)
clos = G.closeness(vertices=neigh)
induced_path = first
G.delete_vertices(first)
while len(neigh) > 0:
     pos = maximum(clos, len(clos))
     j= neigh[pos]
     np.append(induced_path,j)
     print(induced_path)
     neigh = np.setdiff1d(neigh,j)
     G.delete_vertices(neigh)
     neigh = G.neighbors(j)
     clos = G.closeness(vertices=neigh)
     G.delete_vertices(j)
     print(len(induced_path))

當我運行此代碼時,python 給了我這個錯誤:

Cannot create iterator, invalid vertex id, Invalid vertex id

在尋找 j 的鄰居的過程中也存在如下問題:

cannot get neighbors, Invalid vertex id

追溯:

File "E:/inducedpath/indu.py", line 30, in <module> G.delete_vertices(neigh) igraph._igraph.InternalError: Error at c:\projects\python-igraph\vendor\build\igraph\igraph-0.8.0-msvc\src\iterators.c:764: Cannot create iterator, invalid vertex id, Invalid vertex id

文檔中所述,您不應使用頂點的標簽,而應使用 id(s)。

看看這個問題的答案。

對於多個 ID:

to_delete_ids = [x.index for x in G.vs]
G.delete_vertices(to_delete_ids)

對於單個頂點: G.delete_vertices(x.index)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM