关键点错误:Python中的0具有编辑距离

关键点错误:Python中的0具有编辑距离,python,keyerror,Python,Keyerror,有人能告诉我为什么我收到一条关于以下代码第23行的“Key Error:0”消息吗?我正在尝试实现一个编辑距离函数,返回成本和最后一个操作。谢谢 from enum import Enum class Operation(Enum): """Operations""" DELETED = 1 INSERTED = 2 SUBSTITUTED = 3 def __str__(self): return str(self.name.lo

有人能告诉我为什么我收到一条关于以下代码第23行的“Key Error:0”消息吗?我正在尝试实现一个编辑距离函数,返回成本和最后一个操作。谢谢

from enum import Enum


class Operation(Enum):
    """Operations"""

    DELETED = 1
    INSERTED = 2
    SUBSTITUTED = 3

    def __str__(self):
        return str(self.name.lower())


def distances(a, b):
    """Calculate edit distance from a to b"""

    # edit distance
    x = len(a) + 1
    y = len(b) + 1
    cost = {}
    for i in range(0, x):
        cost[i][0] = i
    for j in range(0, y):
        cost[0][j] = j
    for i in range(1, x):
        for j in range(1, y):
            if a[i] == b[j]:
                sub_cost = 0
            else:
                sub_cost = 1
            cost[i][j] = min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost)

            # final operation
            if cost[i - 1][j] + 1 == min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost):
                last_operation = Operation.DELETED
            if cost[i][j - 1] + 1 == min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost):
                last_operation = Operation.INSERTED
            else:
                last_operation = Operation.SUBSTITUTED


    return cost[x][y], last_operation

问题是,当您在空字典上运行
cost[i][0]=i
时,您正在尝试为子字典赋值,但由于尚未初始化字典中的任何值,因此没有可访问的内容,因此出现“键错误”。必须先初始化子字典,然后才能向其添加键/值

for i in range(0, x):
    cost[i] = {}
    cost[i][0] = i

或者,您可以使用设置字典中子项的默认值。

具体是哪一行?能否请您标记代码中报告错误的那一行?错误消息显示时参考了“cost[i][0]=i”行,但现在在根据Sam Hollenbach的回复进行更改之后,最后一行显示相同的错误消息。