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

Python新手求助:计算图节点到原点的欧氏距离

嘿,作为Python新手遇到这个问题太正常啦,我来帮你捋清楚怎么解决~

你的核心问题是:用g.add_nodes_from(pos)添加节点时,只是把pos里的节点编号(比如1、2、3)加到了图里,并没有把对应的(x,y)坐标存在节点的属性中,所以没法直接从节点对象里调用x、y值。下面给你两种简单可行的解决办法:

方法1:添加节点时把坐标存入节点属性

这种方式能让你后续直接从节点本身调用坐标,逻辑更清晰:

import networkx as nx
import matplotlib.pyplot as plt
import math

g = nx.Graph()
pos = {1:(0,0), 2:(5,5), 3:(10,10)}

# 循环遍历pos,把每个节点和对应的坐标作为属性添加到图中
for node, (x, y) in pos.items():
    g.add_node(node, x=x, y=y)

# 计算每个节点到原点(0,0)的欧氏距离
for node in g.nodes:
    x = g.nodes[node]['x']
    y = g.nodes[node]['y']
    # 用距离公式计算,或者用math.hypot更简洁
    distance = math.sqrt((x - 0)**2 + (y - 0)**2)
    print(f"节点{node}到原点的距离:{distance:.2f}")

# 绘图验证节点位置
nx.draw(g, pos, with_labels=True, node_size=700)
plt.show()
方法2:直接利用已有的pos字典获取坐标

如果你不想修改节点的添加方式,也可以直接用你定义好的pos字典——它本身就是节点到坐标的映射,直接拿来用就行:

import networkx as nx
import matplotlib.pyplot as plt
import math

g = nx.Graph()
pos = {1:(0,0), 2:(5,5), 3:(10,10)}
g.add_nodes_from(pos)

# 直接从pos中取出对应节点的坐标计算距离
for node in g.nodes:
    x, y = pos[node]
    # math.hypot(x,y)等价于sqrt(x² + y²),专门用来计算点到原点的欧氏距离
    distance = math.hypot(x, y)
    print(f"节点{node}到原点的距离:{distance:.2f}")

# 绘图验证
nx.draw(g, pos, with_labels=True, node_size=700)
plt.show()

两种方法都能帮你顺利计算出节点到原点的欧氏距离,你可以根据自己的习惯选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:25:47