在具有最高属性值的节点中选择随机节点

时间:2013-05-20 18:39:44

标签: networkx

我想在高度互联的网络中选择并打印三个节点。从给定节点开始,该函数应选择具有最高度中心性的相邻节点的步行的第二个节点。

在平局的情况下,我想让程序在这些节点之间随机选择。

这是我到目前为止所拥有的:

import networkx as nx
from random import choice
g =nx.Graph()
g.add_nodes_from(range(1,5))
g.add_edges_from([(1,5),(2,5),(3,5),(4,5), (1,2),(2,3),(3,4),(4,5)])

nx.set_node_attributes(g,'degree_cent',nx.degree_centrality(g))
degree_walk =[]                 

node1=g.nodes()[2]
degree_walk.append(node1)
for node2 in g.neighbors(node1):
    if max(g.node[node2]['degree_cent'],  g.node[node2]['degree_cent'].get):
            node2 = choice(g.neighbors(node1))
            degree_walk.append(node2)
print degree_walk

1 个答案:

答案 0 :(得分:1)

这里你去(受this SO answer启发,找到字典最大值的关键值):

# Find all the neighbors with maximum centrality:
highest_centrality = max([g.node[n]['degree_cent'] 
                          for n in g.neighbors(node1)) 
most_central_neighbors = [n for n in g.nodes() 
                          if g.node[n]['degree_cent'] == highest_centrality]
# Pick one at random:
random_central_neighbor = choice([most_central_neighbors])
# Add it to the list:
degree_walk.append(random_central_neighbor)
print degree_walk

请注意,如果您不关心关系(并且乐意接受原始列表中的第一个关系),您可以这样做:

# Find all the neighbors with maximum centrality:
most_central_neighbors = max(g.neighbors(node1), 
                             key=lambda(n): g.node[n]['degree_cent'])