簡體   English   中英

為什么我的代碼不斷拋出KeyError?

[英]Why does my code keep throwing a KeyError?

對於我的一生,我無法弄清楚為什么我的代碼會拋出KeyError。 我覺得值應該在那里-我在第一個for loop中將它們全部添加了,並且將它們添加到的列表也不為空(我已經檢查了print語句)。 那么為什么第54行會不停地拋出KeyError? 我敢肯定我只是忽略了一些東西,但是整整工作了一天之后,我還是很困。

這里使用的函數(graph()和shortest_path()等)在這里

edgeData具有以下結構:

{string value: [list of string values that are groupings of the values in the dictionary's keys]}

tagUsers具有以下結構:

{string value: [grouped lists of string values found in edgeData]}

提前致謝。

from collections import defaultdict, deque
import json

class Graph(object):
    def __init__(self):
        self.nodes = set()
        self.edges = defaultdict(list)
        self.distances = {}

    def add_node(self, value):
        self.nodes.add(value)

    def add_edge(self, from_node, to_node, distance):
        self.edges[from_node].append(to_node)
        self.edges[to_node].append(from_node)
        self.distances[(from_node, to_node)] = distance


def dijkstra(graph, initial):
    visited = {initial: 0}
    path = {}

    nodes = set(graph.nodes)

    while nodes:
        min_node = None
        for node in nodes:
            if node in visited:
                if min_node is None:
                    min_node = node
                elif visited[node] < visited[min_node]:
                    min_node = node
        if min_node is None:
            break

        nodes.remove(min_node)
        current_weight = visited[min_node]

        for edge in graph.edges[min_node]:
            try:
                weight = current_weight + graph.distances[(min_node, edge)]
            except:
                continue
            if edge not in visited or weight < visited[edge]:
                visited[edge] = weight
                path[edge] = min_node

    return visited, path


def shortest_path(graph, origin, destination):
    visited, paths = dijkstra(graph, origin)
    full_path = deque()
    _destination = paths[destination]

    while _destination != origin:
        full_path.appendleft(_destination)
        _destination = paths[_destination]

    full_path.appendleft(origin)
    full_path.append(destination)

    return visited[destination]
if __name__ == '__main__':
    edgeData = {'a': ['c', 'd'], 'b': ['d'], 'c': ['d'], 'd': ['a', 'b']}
    tagUsers = {'hashtag1': ['a', 'c', 'd'], 'hashtag2': ['b'], 'hashtag3': ['b', 'd']}
    shortestpaths = {}

    graph = Graph()

    users = []


    # calls function, builds graph with data in edgeData
    for key, value in edgeData.items():
        users.append(key)
        graph.add_node(key)

        for each in value:
            graph.add_edge(key, each, 1)

    # determines how many users used each hashtag
    hashtags = {}
    for key, value in tagUsers.items():
        tmpTags = key
        count = len(value)
        hashtags[key] = count

    # normally determines which hashtag was used the most
    # Here, it's pre-set
    topTag = ['hashtag1']

    # calculates the shortest path from each user to another user
    # that uses the most-used hashtag
    count = 0
    if count < 1:
        for key, value in edgeData.items():
            tmpDict = {}
            for tag in topTag:
                shortest = 10000
                for k, v in tagUsers.items():
                    if k == tag:
                        for each in v:
                            flag = False
                            if key != each
                                flag = True
                                tmpShort = shortest_path(graph, key, each)
                                if tmpShort < shortest:
                                    shortest = tmpShort
                if flag:
                    tmpDict[tag] = shortest
            shortestpaths[key] = tmpDict
            count += 1

目標是使每個用戶中的shortestpaths的數據包含與使用頂部#標簽的另一個用戶的最短距離

函數調用引用了此代碼,由github上的mdsrosa提供。

具體來說,錯誤會在`_destination = path [_destination]中的shortest_path shortest_path()中引發

添加一些記錄到shortest_path顯示問題:

def shortest_path(graph, origin, destination):
    print 'shortest_path     Origin:%s  Destination:%s' % (origin, destination)
    visited, paths = dijkstra(graph, origin)
    full_path = deque()
    print 'paths: %s' % paths
    _destination = paths[destination]

結果是:

shortest_path     Origin:a  Destination:a
paths: {'c': 'a', 'b': 'd', 'd': 'a'}
Traceback (most recent call last):
  File "e.py", line 43, in <module>
    tmpShort = dj.shortest_path(graph, key, each)
  File "E:\kiribati\dijkstra.py", line 61, in shortest_path
    _destination = paths[destination]
KeyError: 'a'

您需要處理起點和終點相同的極端情況

一種選擇是在調用shortest_path之前添加檢查if key == each

    for k, v in tagUsers.items():
        if k == tag:
            for each in v:
                if key == each:
                    continue
                tmpShort = dj.shortest_path(graph, key, each)
                if tmpShort < shortest:
                    shortest = tmpShort
    tmpDict[tag] = shortest

此外,從改變你的循環變量kvkeyvalueeach的東西,描述了實際數據

暫無
暫無

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

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