Это можно решить следующим образом:
Код:
import community
import networkx as nx
# Generate test graph
G = nx.fast_gnp_random_graph(100, 0.1)
# Relabel nodes
G = nx.relabel_nodes(G, {i: f"node_{i}" for i in G.nodes})
# Compute partition
partition = community.best_partition(G)
# Get a set of the communities
communities = set(partition.values())
# Create a dictionary mapping community number to nodes within that community
communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}
# Filter that dictionary to map to first sort the nodes in the community by degree, then take the top 5.
highest_degree = {k: sorted(v, key=lambda x: G.degree(x))[-5:] for k, v in communities_dict.items()}
Выход:
>>> highest_degree
{0: ['node_91', 'node_24', 'node_19', 'node_8', 'node_83'],
1: ['node_54', 'node_69', 'node_88', 'node_48', 'node_84'],
2: ['node_79', 'node_34', 'node_52', 'node_46', 'node_36'],
3: ['node_98', 'node_96', 'node_86', 'node_76', 'node_30'],
4: ['node_29', 'node_40', 'node_10', 'node_90', 'node_32'],
5: ['node_94', 'node_97', 'node_59', 'node_25', 'node_37'],
6: ['node_31', 'node_56', 'node_57', 'node_62', 'node_63']}