将 random.choice() 与 networkx 一起使用时出现问题

Issue with using random.choice() with networkx

所以,我在使用这个 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() returns 一个 NodeView 对象,它是一个包含每个节点数据的字典类型。如文档中所述: “如果不需要您的节点数据,则使用表达式 for n in G 或 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()

输出:

G.nodes() returns a 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, c2, weight=w)