Python - 重复给定函数 n 次

标签 python dictionary networkx repeat

以下代码查找给定图“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 中的节点。我必须手动读取确定的社区数量,并手动重复和编辑每个号码的代码。我怎样才能应用一个自动重复此代码的函数,而不是'0',我可以有'n'?

最佳答案

假设你的分区存储在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]

关于Python - 重复给定函数 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010818/

相关文章:

python - 排名之间的距离

Python 查找两个字典是否具有相同的按值划分的键

c# - 如何使用 Linq 从 XML 创建字典数组?

python - 找到具有以下属性的边,如果您跟随它们,您将必须回到刚刚离开的节点才能到达图形的其余部分

python - python 中的派系

python - 使用生成器模拟索引方法

python - 定义 OrderedDict 时出错 - ValueError : too many values to unpack

python - 是否可以在 Networkx 图中混合不同形状的节点?

python - 如何将列表的每个元素分配给单独的变量?

c# - 是否可以直接 Linq 到字典?