为什么我的代码不断抛出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提供的

具体来说,该错误会抛出在shortest_path()“ _destination =路径[_destination]”中

杰里米·K

添加一些日志记录以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'

您需要处理起点和终点相同的极端情况

一种选择是if key == each在致电之前添加支票shortest_path

    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的东西,描述了实际数据

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

为什么我的PanelND工厂抛出KeyError?

来自分类Dev

为什么我抛出NullPointerException

来自分类Dev

当我的lua代码抛出错误时,为什么不能捕获luabind :: error异常?

来自分类Dev

URLClassLoader不断抛出ClassNotFoundException。我究竟做错了什么?

来自分类Dev

为什么git不断向我抛出“合并”警告消息?

来自分类Dev

为什么此代码不断被“终止”?

来自分类Dev

GitHub不断抛出“无法提交子模块”错误,我不知道为什么。有任何想法吗?

来自分类Dev

为什么在出现异常后我的代码会不断重复自身?

来自分类Dev

为什么我的形象不断重复?

来自分类Dev

为什么我的代码出现Kivy KeyError :?

来自分类Dev

我在shared_ptr中遇到问题。为什么这段代码会抛出SEGV?

来自分类Dev

为什么我不断得到Null?

来自分类Dev

我的代码中出现KeyError:'',但我不明白为什么

来自分类Dev

为什么抛出异常而不是让代码抛出异常?

来自分类Dev

为什么我不断收到NoSuchElementException?

来自分类Dev

为什么我的SQL代码抛出错误

来自分类Dev

URLClassLoader不断抛出ClassNotFoundException。我究竟做错了什么?

来自分类Dev

为什么我的绘图代码不断产生模糊的形状?

来自分类Dev

为什么我的ActionListener不断重复?

来自分类Dev

为什么我的命名管道不断被修改?

来自分类Dev

为什么此代码不断被“终止”?

来自分类Dev

为什么新贵不断刷新我的流程?

来自分类Dev

为什么我的递归不断抛出StackOverflow错误?

来自分类Dev

Android:为什么我的onResume()DialogInterface不断循环不断?

来自分类Dev

为什么这段代码会抛出 MalformedURLException?

来自分类Dev

为什么我不断收到预期声明

来自分类Dev

为什么我的 SQL 代码会抛出转换错误?

来自分类Dev

为什么我的代码会抛出错误消息?

来自分类Dev

为什么我在这行代码上不断收到“意外令牌”错误?

Related 相关文章

  1. 1

    为什么我的PanelND工厂抛出KeyError?

  2. 2

    为什么我抛出NullPointerException

  3. 3

    当我的lua代码抛出错误时,为什么不能捕获luabind :: error异常?

  4. 4

    URLClassLoader不断抛出ClassNotFoundException。我究竟做错了什么?

  5. 5

    为什么git不断向我抛出“合并”警告消息?

  6. 6

    为什么此代码不断被“终止”?

  7. 7

    GitHub不断抛出“无法提交子模块”错误,我不知道为什么。有任何想法吗?

  8. 8

    为什么在出现异常后我的代码会不断重复自身?

  9. 9

    为什么我的形象不断重复?

  10. 10

    为什么我的代码出现Kivy KeyError :?

  11. 11

    我在shared_ptr中遇到问题。为什么这段代码会抛出SEGV?

  12. 12

    为什么我不断得到Null?

  13. 13

    我的代码中出现KeyError:'',但我不明白为什么

  14. 14

    为什么抛出异常而不是让代码抛出异常?

  15. 15

    为什么我不断收到NoSuchElementException?

  16. 16

    为什么我的SQL代码抛出错误

  17. 17

    URLClassLoader不断抛出ClassNotFoundException。我究竟做错了什么?

  18. 18

    为什么我的绘图代码不断产生模糊的形状?

  19. 19

    为什么我的ActionListener不断重复?

  20. 20

    为什么我的命名管道不断被修改?

  21. 21

    为什么此代码不断被“终止”?

  22. 22

    为什么新贵不断刷新我的流程?

  23. 23

    为什么我的递归不断抛出StackOverflow错误?

  24. 24

    Android:为什么我的onResume()DialogInterface不断循环不断?

  25. 25

    为什么这段代码会抛出 MalformedURLException?

  26. 26

    为什么我不断收到预期声明

  27. 27

    为什么我的 SQL 代码会抛出转换错误?

  28. 28

    为什么我的代码会抛出错误消息?

  29. 29

    为什么我在这行代码上不断收到“意外令牌”错误?

热门标签

归档