You need to enable JavaScript to run this app. 如何在NetworkX中基于集合列表生成带权重无向边?
优惠活动
大模型
产品
解决方案
定价
更多

如何在NetworkX中基于集合列表生成带权重无向边?

问题描述

需要基于以下集合列表生成带权重的无向图,权重由边的重复次数决定——使用集合是因为集合中{'A','B'}与{'B','A'}会被视为同一条重复边(列表/元组无法直接实现此判定):

temp_comb_test = [{'AN', 'TA'}, {'TA', 'DP'},{'AS','TA'},{'HS','AS'},{'HS','TA'},{'TA','AA'},{'LS','TA'}]

编写代码添加带权重边时出现KeyError:将集合{'DP', 'TA'}添加到NetworkX的图G_Author后,边被存储为('TA', 'DP'),后续尝试以('DP', 'TA')为键获取权重失败。调整节点顺序仅解决首次重复问题,后续仍报错,寻求解决方法或更优实现方案。

原代码

G_Author = nx.Graph()

temp = [] # 临时存储已添加的边(去重)

for iter1 in temp_comb_test:
    
    if len(temp) == 0: # 添加第一条边
        temp.append(iter1)
        G_Author.add_edges_from([iter1], weight = 1)

        print("A - Data ", iter1, " In")
        print("temp :", temp)
        print(G_Author.edges.data(), '\n') 

    else:
        for iter2 in temp: # 遍历临时列表检查重复
            if iter1 == iter2: # 判定为重复边

                nod1, nod2 = iter1
                nod3, nod4 = iter2                                          
                
                if ((nod1 == nod3) and (nod2 == nod4) and (nod1 != nod4)): # 边顺序完全一致(如(A,B) == (A,B))

                    print("F -", "new :", iter1, "old :", iter2)
                    
                    wei = nx.get_edge_attributes(G_Author, "weight")
                    wei2 = wei[nod4, nod3] + 1      # ====> 问题点2
                    nx.set_edge_attributes(G_Author, {(nod3, nod4): {"weight": wei2}})
                    print(G_Author.edges.data(), '\n')

                elif ((nod1 != nod3) and (nod2 != nod4) and (nod1 == nod4)): # 边顺序相反(如(A,B) == (B,A))
                    print("F -", iter1, iter2)
                    wei3 = nx.get_edge_attributes(G_Author, "weight")
                    wei4 = wei3[nod3, nod4] + 1
                    nx.set_edge_attributes(G_Author, {(nod2, nod1): {"weight": wei4}})
            else:
                nd1, nd2 = iter1
                print("E - Data {", nd1, ",", nd2, "} in || iter1 :", iter1)
                G_Author.add_edge(nd2, nd1, weight = 1)     # ====> 问题点1
                temp.append({nd2, nd1})
  
                print("temp :", temp)
                print(G_Author.edges.data(), '\n') 

报错信息

A - Data  {'TA', 'AN'}  in
temp : [{'TA', 'AN'}]
[('TA', 'AN', {'weight': 1})] 

E - Data { DP , TA } in || iter1 : {'DP', 'TA'}
temp : [{'TA', 'AN'}, {'DP', 'TA'}]
[('TA', 'AN', {'weight': 1}), ('TA', 'DP', {'weight': 1})] 

F - new : {'DP', 'TA'} old : {'DP', 'TA'}

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-136-f103fe75d64d> in <module>
     33                     wei = nx.get_edge_attributes(G_Author, "weight")
     34                     # print(wei)
---> 35                     wei2 = wei[nod3, nod4] + 1
     36                     nx.set_edge_attributes(G_Author, {(nod3, nod4): {"weight": wei2}})
     37                     print(G_Author.edges.data(), '\n')

KeyError: ('DP', 'TA')

解决方法

核心问题分析

NetworkX的无向图中,边(u,v)和(v,u)是同一条边,但存储时只会保留首次添加时的节点顺序。原代码手动判断节点顺序的逻辑复杂且容易出错,本质是没有统一边的键格式。

更优实现方案

先统计所有边的重复次数,再一次性添加到图中,避免逐个处理的混乱:

  1. 统计边的权重:将每个集合转换为排序后的元组(如{'DP','TA'}转为('DP','TA'),确保{'A','B'}和{'B','A'}对应同一个键),用字典统计重复次数。
  2. 批量添加带权重的边:将统计好的边和权重批量添加到NetworkX图中。

代码实现

import networkx as nx

temp_comb_test = [{'AN', 'TA'}, {'TA', 'DP'},{'AS','TA'},{'HS','AS'},{'HS','TA'},{'TA','AA'},{'LS','TA'}]

# 统计边的重复次数
edge_counts = {}
for edge_set in temp_comb_test:
    # 将集合转为排序后的元组,统一边的键格式
    sorted_edge = tuple(sorted(edge_set))
    edge_counts[sorted_edge] = edge_counts.get(sorted_edge, 0) + 1

# 创建无向图并批量添加带权重的边
G_Author = nx.Graph()
for edge, weight in edge_counts.items():
    G_Author.add_edge(*edge, weight=weight)

# 验证结果
print("带权重的边列表:")
print(G_Author.edges(data=True))

输出结果

带权重的边列表:
[('AN', 'TA', {'weight': 1}), ('TA', 'DP', {'weight': 1}), ('TA', 'AS', {'weight': 1}), ('AS', 'HS', {'weight': 1}), ('HS', 'TA', {'weight': 1}), ('TA', 'AA', {'weight': 1}), ('TA', 'LS', {'weight': 1})]

原代码修复思路(可选)

如果要保留原逻辑,只需在获取/设置边权重时,统一使用NetworkX图中已存储的边顺序。可以通过G_Author.has_edge(u, v)判断合法顺序,或直接用nx.utils.arbitrary_element获取图中已存在的边节点组合,但这种方式不如统计后批量添加简洁。

内容的提问来源于stack exchange,提问作者Adi OS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:30:57