我嘗試在 jupyter 筆記本(python 版本 - 3.7.6)上運行的代碼有一個奇怪的問題此鏈接中的代碼 ( https://towardsdatascience.com/to-all-data-scientists-the-one-graph-algorithm-you-need-to-know-59178dbb1ec2 ) 由于 python 而有點過時它所寫的版本。我將“.iteritems”更改為“.items”并且在這部分之前效果很好:graph = Graph(g)graph.add_edge(("Mumbai", "Delhi"),400)graph.add_edge(("Delhi", "Kolkata"),500)graph.add_edge(("Kolkata", "Bangalore"),600)graph.add_edge(("TX", "NY"),1200)graph.add_edge(("ALB", "NY"),800)g = graph.adj_mat()def bfs_connected_components(graph): connected_components = [] nodes = graph.keys() while len(nodes)!=0: start_node = nodes.pop() queue = [start_node] #FIFO visited = [start_node] while len(queue)!=0: start = queue[0] queue.remove(start) neighbours = graph[start] for neighbour,_ in neighbours.items(): if neighbour not in visited: queue.append(neighbour) visited.append(neighbour) nodes.remove(neighbour) connected_components.append(visited) return connected_componentsprint bfs_connected_components(g)它給了我這個錯誤File "<ipython-input-48-660b0e10e666>", line 32 print bfs_connected_components(g) ^ SyntaxError: invalid syntax所以我試著起飛print,只是bfs_connected_components(g)為了找到調試器會返回給我的東西。當我在沒有命令的情況下運行代碼時,print它會返回以下錯誤:AttributeError Traceback (most recent call last)<ipython-input-49-09c142e436e3> in <module> 30 return connected_components 31 ---> 32 bfs_connected_components(g)<ipython-input-49-09c142e436e3> in bfs_connected_components(graph) 14 15 while len(nodes)!=0:---> 16 start_node = nodes.pop() 17 queue = [start_node] #FIFO 18 visited = [start_node]AttributeError: 'dict_keys' object has no attribute 'pop'這很奇怪,因為此鏈接中的先前代碼中有.pop命令,并且它運行良好,沒有任何錯誤,除了表達式.iteritems。
1 回答

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
與您提到的其他問題一樣(例如 中缺少括號print
,以及 iteritems 的項目發生變化),這是一個 Python 版本問題。在 Python 3 中,pop 對 dict_keys 不起作用。
要解決此問題,您可以將其列為一個列表。在您的代碼中,執行nodes = list(graph.keys())
.
添加回答
舉報
0/150
提交
取消