簡體   English   中英

Python - 類型錯誤:function 占用 3 個位置 arguments 但給出了 4 個

[英]Python - TypeError: function takes 3 positional arguments but 4 were given

我正在嘗試在城市和字典之間添加邊緣以及它們之間的距離。 當我嘗試編譯我遇到此錯誤的代碼時,任何人都可以幫助我嗎?

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

在此處輸入圖像描述

我相信您的代碼可以在 .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 的機器上測試它。

如果你想為屬性使用字典,那么你可以使用@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([('聖地亞哥', '洛杉磯', {'距離': 0.4}), ('紐約', '納什維爾', {'距離': 5.6}), ('波士頓', '華盛頓', { “距離”:0.8})])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM