You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为完全图的边添加含函数关联的双重属性?

解决方案

你可以通过两种方式快速添加衍生属性BW,无需针对具体节点对操作,适配任意大小的完全图:

方法一:字典推导式批量生成

利用已生成的attfirst字典,直接推导得到BW属性的字典,再批量设置到图中:

import random
import networkx as nx

def create_random_topology(size):     
    G = nx.generators.complete_graph(size)
    attfirst = {x: random.randint(100, 500) for x in G.edges()}
    nx.set_edge_attributes(G, name="PR", values=attfirst)
    
    # 基于PR属性生成BW属性
    attsecond = {edge: 1 / pr_val for edge, pr_val in attfirst.items()}
    nx.set_edge_attributes(G, name="BW", values=attsecond)
    
    return G

方法二:遍历边直接修改属性

遍历图中所有边,直接从已有的PR属性计算并添加BW:

import random
import networkx as nx

def create_random_topology(size):     
    G = nx.generators.complete_graph(size)
    attfirst = {x: random.randint(100, 500) for x in G.edges()}
    nx.set_edge_attributes(G, name="PR", values=attfirst)
    
    # 遍历每条边,计算并设置BW
    for u, v, attrs in G.edges(data=True):
        attrs['BW'] = 1 / attrs['PR']
    
    return G

两种方法都能实现你需要的效果,最终每条边的属性会符合示例格式:{(0,1): {'PR': 10, 'BW': 0.1}, (0,2): {'PR':5, 'BW':0.2}, ...}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:13:19