Skip to main content
 首页 » 编程设计

python之来自 networkx 的 g.nodes() 不适用于 random.choice()

2024年09月07日8luoye11

我正在尝试在随机节点之间生成随机边,但代码行 ab=choice(G.nodes()) 生成了错误。

import networkx as nx 
import matplotlib.pyplot as plt 
from random import choice 
G=nx.Graph() 
city_set=['a','b','c','d','e','f','g','h'] 
for each in city_set: 
    G.add_node(each) 
ab=choice(G.nodes()) 
print(ab) 

错误

C:\Users\DELL\Anaconda2\envs\untitled\python.exe C:/Users/DELL/Documents/PythonPrograms/Beginning/ntwxproject.py Traceback (most recent call last): File "C:/Users/DELL/Documents/PythonPrograms/Beginning/ntwxproject.py", line 10, in ab=choice(G.nodes()) File "C:\Users\DELL\Anaconda2\envs\untitled\lib\random.py", line 259, in choice return seq[i] File "C:\Users\DELL\Anaconda2\envs\untitled\lib\site-packages\networkx\classes\reportviews.py", line 178, in getitem return self._nodes[n] KeyError: 1

Process finished with exit code 1

我是 python 的新手,请帮助我。

请您参考如下方法:

您可以通过传递 list(G.nodes()) 而不仅仅是 G.nodes() 将 G.nodes() 转换为与 random.choice() 兼容的列表格式。

import networkx as nx 
import matplotlib.pyplot as plt  
from random import choice       
G=nx.Graph()       
city_set=['a','b','c','d','e','f','g','h']  
for each in city_set:      
    G.add_node(each)      
ab= choice(list(G.nodes()))  
print(ab)