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

前端 未结 3 438
梦毁少年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:27

    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 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...

提交回复
热议问题