【问题标题】:Add weight to edge in Network向网络中的边缘添加权重
【发布时间】:2020-10-08 19:40:41
【问题描述】:

我创建了 2 个列表。然后我创建了另一个列表,其中有许多数字 (x,y),它是两个列表之间的混合。 然后,我计算了这对夫妇在我的列表中出现的次数。 现在,我想创建一些带有权重的边。

这是我的代码:

 G = nx.Graph()
 G.add_nodes_from(ID)
 L = []
 ID_1 = df_2['ID_1']
 ID_2 = df_2['ID_2']
 L2 = ID_1 # First List
 L3 = ID_2 #Second List
 L = list(zip(L2, L3)) # Fusion of the list
 #print(L)
 compte = {}.fromkeys(set(L),0)
 for valeur in L:
    compte[valeur] += 1
 print(compte) # Return occurence the couple (a,b)

这是 python 返回的内容:

{(1295, 1485): 1, (232, 941): 1, (28, 653): 50, (376, 1336): 2, (214, 254): 
 3, (202, 954): 1, (1212, 1342): 13, (117, 587): 5, (131, 256): 3, (1216, 
 1232): 1, (190, 836): 2, (798, 921): 2, (32, 893): 1, (376, 1228): 53, (269, 
 836): 9, (90, 605): 2, (184, 240): 22, (63, 179): 717, (240, 778): 4, (413, 
 706): 6, (72, 147): 20, (1237, 1412): 2, (116, 190): 3, (85, 382): 3, (353, 
1594): 1, (214, 267): 5, (227, 960): 1, (290, 491): 1, (450, 480): 3, (1214, 
1401): 5, (205, 649): 5, (743, 998): 1, (440, 960): 1, (1336, 1512): 6, (214, 
388): 1, (267, 480): 6, (79, 200): 4, (101, 447): 26, (92, 893): 1, (1232, 
 1805): 8, (339, 504): 10, (306, 327): 1, (176, 254): 34, (267, 601): 1, 
 (179, 488): 1, (184, 603): 1, (1366, 1512): 1, (464, 886): 4, (257, 327): 1, 
 (480, 601): 16, (265, 447): 3, (638, 958): 121, (424, 440): 4}

如您所见,我有很多数字 [(x,y):z],其中 z 出现。 现在,我想创建边缘 (x,y,weight : z),其中 x 是第一个节点,y 是第二个节点,z 是权重。但我不知道如何编码,您有什么建议吗?

谢谢。

【问题讨论】:

  • 请添加您的代码并输出为文本,而不是图像。

标签: python list networkx


【解决方案1】:

你可以使用

G.add_weighted_edges_from([(edge[0],edge[1],weight) for edge,weight in compte.items()])

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多