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
impo
You can convert G.nodes() into a list format compatible with random.choice() by passing list(G.nodes()) instead of just G.nodes().
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(list(G.nodes()))
print(ab)
G.node usage is replaced by G.nodes from networkx version 2.4.
Hence you might come across this error if you are trying to un an old code which uses G.node as a key(s) identifier.
Replace all G.node with G.nodes or vice versa. depending on teh version you are trying to work.
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).
Edit: I see you added some information - so I added a way to build the edges...
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...