Python 无向图对顶点重新排序

Python 无向图对顶点重新排序,python,graph,numpy,Python,Graph,Numpy,给定一个邻接矩阵和一个新的顶点顺序,我们如何在python中排列图?是否有用于此任务的库?您只需手动构造新的邻接矩阵即可old是旧的邻接矩阵,perm是存储每个新顶点的旧名称的向量,也就是说,如果顶点j移动到顶点i,则perm[i]==j import numpy as np def rearrange(old, perm): n = old.shape[0] new = np.zeros_like(old) for x in xrange(n): f

给定一个邻接矩阵和一个新的顶点顺序,我们如何在python中排列图?是否有用于此任务的库?

您只需手动构造新的邻接矩阵即可
old
是旧的邻接矩阵,
perm
是存储每个新顶点的旧名称的向量,也就是说,如果顶点
j
移动到顶点
i
,则
perm[i]==j

import numpy as np

def rearrange(old, perm):
    n = old.shape[0]
    new = np.zeros_like(old)

    for x in xrange(n):
        for y in xrange(x+1): # only need to traverse half the matrix
            # the matrix is symmetric (because of undirectedness)
            new[y, x] = new[x, y] = old[perm[x], perm[y]]
    return new

(注意,我假设您将邻接矩阵作为密集矩阵存储在
n
×
n
numpy数组中。另外,对于Python3.x,
xrange
应该是
range

您可以手工构造新的邻接矩阵
old
是旧的邻接矩阵,
perm
是存储每个新顶点的旧名称的向量,也就是说,如果顶点
j
移动到顶点
i
,则
perm[i]==j

import numpy as np

def rearrange(old, perm):
    n = old.shape[0]
    new = np.zeros_like(old)

    for x in xrange(n):
        for y in xrange(x+1): # only need to traverse half the matrix
            # the matrix is symmetric (because of undirectedness)
            new[y, x] = new[x, y] = old[perm[x], perm[y]]
    return new
(注意,我假设您正在将邻接矩阵作为密集矩阵存储在
n
×
n
numpy数组中。另外,对于Python 3.x,
xrange
应该是
range

的可能重复