ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python-重复给定函数n次

2019-11-08 19:55:04  阅读:593  来源: 互联网

标签:dictionary repeat networkx python


以下代码查找给定图“ 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”?

解决方法:

假设您的分区存储在node_partition中,然后我们制作一个新字典,该字典由反向键,node_partition的值对组成,这将有助于我们以后减少计算复杂性. (请参阅this for inverting dicitonarythis for getting key with max value in dictionary.)

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]

标签:dictionary,repeat,networkx,python
来源: https://codeday.me/bug/20191108/2010275.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有