【问题标题】:Type Error when trying to append to a list in Python [duplicate]尝试附加到 Python 中的列表时键入错误 [重复]
【发布时间】:2015-05-30 15:45:21
【问题描述】:

我正在编写代码来对测试和训练数据矩阵执行 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

当我运行代码时,我在该行遇到类型错误

k_values.append((sortedLabels[x]))

我得到 TypeError: 'Nonetype' object has no attribute 'getitem' 我不确定为什么。

非常感谢任何帮助!

【问题讨论】:

  • labeled.sort() 对列表就地进行排序并返回None。所以sortedLablesNone
  • @MartijnPieters 这应该是一个答案:)
  • @Nizil:我已经在 other 问题中以更一般的方式回答了这个问题。 :-)
  • 当然可以!!我不敢相信我没有看到,非常感谢大家:)

标签: python list append typeerror knn


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 2020-01-18
    • 2022-10-14
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2012-11-25
    相关资源
    最近更新 更多