选择随机节点(Python)时出错



这是我的Python代码如下:

import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)

在编译代码时,我遇到了如下错误:-

$ python cities.py 
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq 
is empty
File "/usr/local/lib/python2.7/dist- 
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7

我还创建了对 Pyhton 的恶意环境,但它再次显示出相同的错误。 另外,我尝试在Google上找到一些东西并检查解决方案,但是没有人遇到类似的问题。

更改

c1=choice(g.nodes())
c2=choice(g.nodes())

c1=choice(list(g))
c2=choice(list(g))

应该工作。

g.nodes()返回NodeView而不是节点列表。

import random 
import networkx as nx 
costs = [] 
value=100  
while(value<=2000):     
costs.append(value)     
value+=100 
print (costs)  
while(G.number_of_edges()<16):     
c1 = random.choice(list(G.nodes()))     
c2 = random.choice(list(G.nodes()))     
if c1!=c2 and G.has_edge(c1,c2)==0:         
w= random.choice(costs)         
G.add_edge(c1,c2,weight = w)       

尝试此代码,因为视频中显示的随机语法存在一些错误。我已经粘贴了我的代码,测试它。

G.nodes() 需要返回一个列表,但这里返回一个 NodeView。因此将 G.nodes() 更改为 list(G.nodes())

最新更新