Error in Selecting Random Nodes(Python)

时间:2018-07-24 10:21:32

标签: python graph

Here is My Python Code is given below:-

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)

and while compiling the code I got the error stated below:-

$ 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

I also created vitual enviourment of Pyhton but again it shows the smae error. Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.

2 个答案:

答案 0 :(得分:1)

更改

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

进入

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

应该工作。

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

答案 1 :(得分:1)

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())