Python - 重复执行给定的函数n次

3
以下代码为给定的图 'G' 查找社区,并根据它们所属的社区将节点分配值从0到n。然后,该代码为每个社区创建新的子图,并在其中找到具有最高度数的节点。最后,每个子图中的顶级节点被整合到一个总字典中:
   G = 'max : john', 'max : tom', 'jim : john'....'jack : james'
   node_partition = dict(community_louvain.best_partition(G))   

   print node_partition = max: 1, john: 0, james: 3, jim: 4,...tom: 0

   """number of communities = n = list(set(node_partition.values()))"""

   dict0 = {k: v for k, v in node_partition.items() if v !=[0]} 
       G0 = G.copy()   
       G0.remove_nodes_from(dict0)
       degree0 = dict(G.degree(G0))
       degree0_dict = dict(sorted(degree0.items(), key=operator.itemgetter(1), reverse=True)[:1])

   star_dict = {**degree0_dict, **degree1_dict....**degreek_dict)

这种方法是可行的,但是一个图可以有n个社区,正如您所看到的代码仅适用于社区0中的节点。我必须手动读取确定社区的数量,并手动重复和编辑每个数字的代码。如何应用一个函数来自动重复这段代码,使得我可以有'n'而不是'0'?

1个回答

2
假设您的分区存储在node_partition中,那么我们将创建一个新字典,其中包含node_partition的反转键值对,这将有助于我们以后减少计算复杂度。(请参考此处反转字典此处获取字典中最大值对应的键。)
def invert(d):
    """Turn {a:x, b:x} into {x:[a,b]}"""
    r = {}
    for k, v in d.items():
        r.setdefault(v, []).append(k)
    return r

invert_partition = invert(node_partition)
# { 0 :[tom, john] , 1: [mike, elton] ... }

max_deg_per_comm = {}
#iterate over each community
for community_id in invert_partition.keys():
    #Extract the sub graph containing the community nodes
    temp_graph = G.subgraph(invert_partition[community_id])

    #Extract the degrees in the subgraph
    temp_degree = dict(temp_graph.degree())

    #Store it in a dictionary, with key as community_id and value as the node with max degree
    max_deg_per_comm[community_id] = max(temp_degree, key=lambda x: temp_degree[x])

现在您可以使用词典 max_deg_per_comm 来获取节点。假设您想要找到社区0的节点,您可以使用:
max_deg_per_comm[0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接