首页 文章

来自networkx的g.nodes()无法使用random.choice()

提问于
浏览
1

我试图在随机节点之间生成随机边缘,但代码行 ab=choice(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(G.nodes())
print(ab)

错误

C:\ Users \ DELL \ Anaconda2 \ envs \ untitled \ python.exe C:/Users/DELL/Documents/PythonPrograms/Beginning/ntwxproject.py Traceback(最近一次调用最后一次):文件“C:/ Users / DELL / Documents / PythonPrograms / Beginning / ntwxproject.py“,第10行,在ab = choice(G.nodes())文件”C:\ Users \ DELL \ Anaconda2 \ envs \ untitled \ lib \ random.py“,第259行,在选择中返回seq [i]文件“C:\ Users \ DELL \ Anaconda2 \ envs \ untitled \ lib \ site-packages \ networkx \ classes \ reportviews.py”,第178行,在getitem中返回self._nodes [n] KeyError :1进程以退出代码1结束

我是python的新手,帮助我 .

1 回答

  • 0

    由于它不是100%清楚您接下来要做什么,我尝试提供一些关于如何将 random.choice() 与您的城市列表结合使用的提示(请注意它是"list",而不是"set" - 更好的标识符将是city_list) .

    编辑:我看到你添加了一些信息 - 所以我添加了一种构建边缘的方法......

    你的主要问题是 G.nodes() 是一个 <class 'networkx.classes.reportviews.NodeView'> 而不是一个简单的列表(即使它的字符串表示看起来像一个列表) .

    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())
    

    我希望这能有所帮助...

相关问题