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

NetworkX技术疑问:为何边会被当作节点添加?添加边后节点列表为何新增0、1、2?

Why NetworkX Adds Edges' Endpoints as Nodes (And Your Code Example Explained)

Let’s break down your two questions one by one—they’re tied to the same core behavior in NetworkX.

1. Why do edges get added as nodes?

NetworkX has a deliberate, convenience-focused design choice here: when you add an edge between two nodes that don’t already exist in the graph, it automatically creates those nodes for you.

This saves you from having to manually pre-add every node before connecting them with edges. For example, if you run G.add_edge('alice', 'bob') on an empty graph, NetworkX will first add both 'alice' and 'bob' as nodes, then create the edge between them. It’s handy for quick graph building, but can surprise you if you’re not expecting it!

2. Why does your code add 0, 1, 2 as nodes?

Let’s walk through your code step by step to see the issue:

  • First, you add nodes that are tuples: (0,0,0), (1,0,0), (1,1,0). In Python, these are completely distinct objects from the integers 0, 1, 2—they don’t count as the same nodes.
  • Next, you try to add edges between the integers (0,1) and (1,2). NetworkX checks if these integer nodes exist in the graph, and they don’t (the existing nodes are tuples, not plain integers).
  • Following its default behavior, NetworkX creates the integer nodes 0, 1, 2 and then adds the edges between them. That’s why those integers appear in your final node list.

If you wanted to connect your tuple nodes instead, you’d need to use the tuples as edge endpoints. For example, to link (0,0,0) to (1,0,0), your edges list should look like [((0,0,0), (1,0,0)), ((1,0,0), (1,1,0))].


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:52:43