首页 > 解决方案 > 将 random.choice() 与 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

标签: pythonnetworkxsocial-networking

解决方案


G.nodes()返回一个 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()

输出: 在此处输入图像描述


推荐阅读