问题描述
我正在尝试在随机节点之间生成随机边,但是代码行ab=choice(G.nodes())
正在生成错误.
I'm trying to generate random edges between random nodes but the line of code ab=choice(G.nodes())
is generating errors.
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
G=nx.Graph()
city_set=['a','b','c','d','e','f','g','h']
for each in city_set:
G.add_node(each)
ab=choice(G.nodes())
print(ab)
错误
以退出代码1完成的过程
Process finished with exit code 1
我是python的新手,请帮帮我.
I'm new to python, help me with it.
推荐答案
由于尚不能100%明确下一步要做什么,因此我尝试对如何结合使用random.choice()
和城市列表提供一些提示(请注意,它是一个列表",而不是集合",更好的标识是city_list).
Since it is not 100% clear what you want to do next, I try to give some hints on how to use random.choice()
in combination with your city list (please note it's a "list", not a "set" - a better identifyer would be city_list).
我看到您添加了一些信息-所以我添加了一种构建边缘的方法...
I see you added some information - so I added a way to build the edges...
您的主要问题是,G.nodes()
是一个<class 'networkx.classes.reportviews.NodeView'>
而不是一个简单的列表(即使其字符串表示形式看起来像一个列表).
Your main problem is, that G.nodes()
is a <class 'networkx.classes.reportviews.NodeView'>
and not a simple list (even though its string representation looks like a list).
import networkx as nx
import matplotlib.pyplot as plt
import random
G=nx.Graph()
city_list=['a','b','c','d','e','f','g','h']
# this is a bit easier then adding each node in a loop
G.add_nodes_from(city_list)
# show type and content of G.nodes()
print(G.nodes())
print(type(G.nodes()))
# based on your old code:
for _ in city_list:
ab=random.choice(city_list)
print(ab)
print("list is now", city_list)
# generate n random edges
n=5
for _ in range(n):
# random.sample(city_list, 2) gives a 2-tuple from city list
# The '*'-operator unpacks the tuple to two input values for the .add_edge() method
G.add_edge(*random.sample(city_list, 2))
print("Edges generated:", G.edges())
我希望这会有所帮助...
I hope this helps a bit...
这篇关于来自networkx的g.nodes()无法与random.choice()一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!