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

前端 未结 3 436
梦毁少年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)
    
    0 讨论(0)
  • 2021-01-21 15:24

    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.

    0 讨论(0)
  • 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 <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...

    0 讨论(0)
提交回复
热议问题