查找具有最大连接边的节点和节点的连接边数

时间:2017-06-13 23:08:31

标签: python networkx

在图表中,如何找到节点的连接(直接绑定)边数? 然后,这将是微不足道的,但如果有任何直接的方法来找到连接到它们的最大边缘的唯一(s)节点,那将是不错的。
我使用的是Python 2.7和Networkx。

到现在为止,我这样做:

sG            = list(nx.connected_component_subgraphs(G)) # sG is a sub_graph of main graph G
nb_sG         = len(sub_graphs)
max_con_node  = list()
for m in xrange(nb_sG):
    sG_nodes      = [(node, len(sG[m].edges(node)), sG[m].edges(node)) for node in sG[m].nodes()]
    connexions    = [i[1] for i in sG_nodes]
    idx           = [i for i,x in enumerate(connexions) if x==max(connexions)]
    max_con_node.append((max(connexions), [sG_nodes[i][0] for i in idx]))

感谢。

2 个答案:

答案 0 :(得分:1)

编辑 - 我已针对新版本的networkx进行了更新。一般情况下,请查看Migration Guide,了解如何将代码从networkx 1.11更新为2.x。

我认为您在询问如何查找节点有多少条边。这被称为节点的

对于 networkx v2.x G.degree(node )为您提供节点的dgree,而G.degree()是一个' DegreeView'宾语。它可以使用dict(G.degree())转换为dict。

G = nx.Graph()
G.add_edges_from([[1,2],[1,3],[2,4],[2,5]])
G.degree()
> DegreeView({1: 2, 2: 3, 3: 1, 4: 1, 5: 1})
max(dict(G.degree()).items(), key = lambda x : x[1])
> (2,3)

networkx v1.11 及更低版本: G.degree(node)为您提供节点的度数,G.degree()是一个dict,其键是节点,其值是相应的度数。

所以max(G.degree().items(), key = lambda x: x[1])是一个简单的单行,为最大程度的节点返回(node,degree)。

以下是一个例子:

G = nx.Graph()
G.add_edges_from([[1,2],[1,3],[2,4],[2,5]])
G.degree()
> {1: 2, 2: 3, 3: 1, 4: 1, 5: 1}
max(G.degree().items(), key = lambda x: x[1])
> (2,3)

答案 1 :(得分:0)

您似乎正在使用邻接列表来表示图表。因此,要查找连接到节点的边数,可以找到该节点的邻接列表的大小。

要查找边连接最多的节点,可以遍历所有节点并找到边连接最多的节点。如果必须经常重复此操作,则可以保留指向具有最多边缘的节点的指针,只需检查并在每次连接额外边缘或添加新节点时将其替换为新节点。

查看维基百科页面以获取更多信息: https://en.wikipedia.org/wiki/Adjacency_list

相关问题