g.nodes() from networkx is not working with random.choice()

前端 未结 3 431
梦毁少年i
梦毁少年i 2021-01-21 15:04

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         


        
3条回答
  •  囚心锁ツ
    2021-01-21 15:06

    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)
    

提交回复
热议问题