为何SCI2脚本可用[:]获取NetworkX节点列表而我无法实现?
g.nodes[:] Doesn't Work in Modern NetworkX & How to Fix It Hey there! Let's clear up this confusion—you're totally right that Python/NetworkX version differences are the root cause here, so let's break it down simply:
The Core Issue: g.nodes Changed Its Return Type
In older versions of NetworkX (common with Python 2), g.nodes directly returned a list of nodes. That's why the SCI2 script could use [:] to slice and create a copy of the list.
But in modern NetworkX (2.0+), which is built for Python 3, g.nodes returns a NodeView object—this is a dynamic, efficient view of the graph's nodes, not a static list. Since views don't support slicing with [:], your code throws an error.
Solutions to Get What You Need
Here are straightforward fixes depending on your goal:
Get a list of all node IDs
Just convert theNodeViewto a list explicitly:import networkx as nx g = nx.Graph() g.add_node(1, size=11) g.add_node(2, size=12) a = list(g.nodes) print(a) # Output: [1, 2]Get nodes along with their attributes
If you need attribute data too, useg.nodes(data=True)and convert to a list—each item will be a tuple of(node_id, attribute_dict):nodes_with_attrs = list(g.nodes(data=True)) print(nodes_with_attrs) # Output: [(1, {'size': 11}), (2, {'size': 12})]Modify node attributes directly
You don't even need a list copy to modify attributes! Access and update them directly via theNodeView:# Update the size of node 1 g.nodes[1]['size'] = 15 print(g.nodes[1]['size']) # Output: 15
Why This Change Happened
NetworkX switched to view objects for efficiency—views avoid unnecessary copies of node/edge data, and they automatically reflect graph changes (e.g., new nodes added later show up in the view without re-fetching). The old list approach was far less efficient for large graphs.
内容的提问来源于stack exchange,提问作者LiuQiang8650

