python - 将 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
解决方案
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()
推荐阅读
- python - 推文搜索返回 0
- visual-studio-code - VS Code Loading React file icon instead of JS file icon
- javascript - firestore loading data in array javascript
- r - R:GLM 模型和 optim() 包之间估计参数的差异
- javascript - 谁能告诉我为什么这个循环永远运行?
- python - 字符串到python中的数组列表
- flutter - flutter build ios耗时很长,一个多小时
- laravel - 如何使用 auth() 验证用户登录 laravel
- r - 读取通过 R 中的 API 导入的 .nc 文件
- python - 将接收到的图像存储在内存中是一个很好的解决方案吗?