在networkx中使用random.choice的问题

问题描述

因此,我在使用此python脚本时遇到了错误,我是python的新手,也许犯了一个愚蠢的错误,请帮帮我。

    import networkx as nx
    import matplotlib.pyplot as plt
    import random
    
    G=nx.Graph()
    city_set=['Ranchi','Delhi','Mumbai','Kolkata','Jaipur','Pune','Surat','Chennai']
    
    for each in city_set:
        G.add_node(each)
    
    # nx.draw(G,with_labels=1)
    # plt.show()
    #print(G.nodes())
    
    # name=random.choice(list(G.nodes()))
    # print(name)
    
                                    # Adding edges
        
    costs=[]
    value=100
    
    while(value<2000):
        costs.append(value)
        value+=100
        
    
    while(G.number_of_edges()<16):
        c1=random.choice(G.nodes())
        c2=random.choice(G.nodes())
        
        if (c1!=c2)and (G.has_edge(c1,c2))==0:
            w=random.choice(costs)
            G.add_edge(c1,c2,weight=w)
            
            
    nx.draw(G,with_labels=1)
    plt.show()

我得到的错误是:-

KeyError                                  Traceback (most recent call last)
<ipython-input-29-67a2861315c5> in <module>
     13 print(G.nodes())
     14 
---> 15 name=random.choice(list(G.nodes()))
     16 print(name)
     17 

D:\ANACONDA\lib\random.py in choice(self,seq)
    260         except ValueError:
    261             raise IndexError('Cannot choose from an empty sequence') from None
--> 262         return seq[i]
    263 
    264     def shuffle(self,x,random=None):

D:\ANACONDA\lib\site-packages\networkx\classes\reportviews.py in __getitem__(self,n)
    275 
    276     def __getitem__(self,n):
--> 277         ddict = self._nodes[n]
    278         data = self._data
    279         if data is False or data is True:

KeyError: 2

解决方法

G.nodes()返回一个NodeView对象,该对象是一个字典类型,其中包含每个节点的数据。如文档中所述: “如果不需要您的节点数据,则将表达式用于G中的n或list(G)更为简单和等效。”

使用强制转换为G.nodes()上的列表: 固定:

import networkx as nx
import matplotlib.pyplot as plt
import random

G=nx.Graph()
city_set=['Ranchi','Delhi','Mumbai','Kolkata','Jaipur','Pune','Surat','Chennai']

for each in city_set:
    G.add_node(each)

# nx.draw(G,with_labels=1)
# plt.show()
#print(G.nodes())

# name=random.choice(list(G.nodes()))
# print(name)

                                # Adding edges

costs=[]
value=100

while(value<2000):
    costs.append(value)
    value+=100


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)


nx.draw(G,with_labels=1)
plt.show()

输出: enter image description here

,

G.nodes()返回一个NodeView,并且当随机函数尝试通过其索引选择元素时,它会失败,因为找不到它。 解决方案可能包括在代码中使用list(G.nodes())
更好的选择是使用random.sample直接选择2个元素,而不是一次选择一个,然后检查它们是否相同。

G.add_nodes_from(city_set)
costs = list(range(100,2000,100))

while(G.number_of_edges() < 16):
    c1,c2 = random.sample(city_set,2)
    if not G.has_edge(c1,c2):
       w = random.choice(costs)
       G.add_edge(c1,weight=w)