Python - TypeError:函数需要3个位置参数,但是给出了4个

时间:2017-11-18 18:43:18

标签: python networkx

我试图在城市和字典之间添加边距和它们之间的距离。 当我尝试编译代码时,我遇到了这个错误,有人可以帮助我吗?

import networkx as nx

cities = nx.Graph()
cities.add_edge('San Diego','LA',{'distance':0.4})
cities.add_edge('NY','Nashville',{'distance':5.6})
cities.add_edge('Boston','DC',{'distance':0.8})

enter image description here

2 个答案:

答案 0 :(得分:1)

我相信你的代码可以在networkx 2.0中运行(它似乎对我有用),但不适用于networkx 1.11。

在阅读networkx 1.11的文档时,看起来您需要执行

cities.add_edge('Boston', 'Nashville', distance=0.4})

cities.add_edge('Boston', 'Nashville', attr_dict = {'distance':0.4})

但是我无法在拥有v2.0的机器上轻松测试它。

答案 1 :(得分:1)

如果您要使用字典作为属性,则可以使用@Joel第二个示例

cities.add_edge('Boston', 'Nashville', attr_dict = {'distance':0.4})

但是在这种情况下,您会得到'attr_dict'作为属性,在其中您将拥有字典。这样。

cities.edges(data=True) 

将返回

  

EdgeDataView([(('波士顿','纳什维尔',{'attr_dict':{'距离':   0.4}})])

仅在属性中获取字典的方法是add_edges_from()

cities.add_edges_from([('San Diego','LA',{'distance':0.4})])
cities.add_edges_from([('NY','Nashville',{'distance':5.6}),
('Boston','DC',{'distance':0.8})])

cities.edges(data=True) 

将返回

  

EdgeDataView([('圣地亚哥','LA',{'距离':0.4}),('NY','纳什维尔',{'距离':5.6}),('波士顿','DC ',{'distance':0.8}))))