尝试在Python中附加到列表时发生类型错误

2024-09-24 12:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写代码来对测试和训练数据的矩阵执行k-NN搜索。有三个正在讨论的矩阵:测试数据、训练数据和一列矩阵,它包含训练数据的每一行向量的相应类。我定义了一个函数,当给出距离矩阵的行时,将每个距离与一个类配对,并返回k个最小距离及其类。这里是函数

def closest(distanceRow, classes, k):
    labeled = []
    for x in range(distanceRow.shape[0]):
        # | each element in the row corresponds to the distance between one      training vector
        # | and one test vector. Each distance is paired with its respective  training
        # | vector class.
        labeled.append((classes[x][0], distanceRow[x]))
    # | The list of pairs is sorted based on distance.
    sortedLabels = labeled.sort(key=operator.itemgetter(1))
    k_values = []
    # | k values are then taken from the beginning of the sorted list,  giving us our k nearest
    # | neighbours and their distance.
    for x in range(k):
        k_values.append((sortedLabels[x]))
    return k_values

当我运行代码时,我在行中得到一个类型错误

^{pr2}$

我得到TypeError:“Nonetype”对象没有属性“getitem”,我不知道为什么。在

非常感谢任何帮助!在


Tags: the数据函数代码in距离forrange
1条回答
网友
1楼 · 发布于 2024-09-24 12:25:11

list.sort()不返回任何内容(如here)所示。在

必须先调用your_list.sort(),然后用your_list执行操作。在

相关问题 更多 >