Type Error when trying to append to a list in Python

Question:

I am writing code to perform a k-NN search on matrices of test and training data. There are three matrices in question; the test data, the training data and matrix that is one column and contains the respective classes for each row vector of the training data. I have defined a function that when give the row of a distance matrix, pairs each distance with a class and returns the k smallest distances with their classes. Here is the function;

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

When I run the code I get a type error at the line

k_values.append((sortedLabels[x]))

I get TypeError: ‘Nonetype’ object has no attribute ‘getitem‘ and I am unsure as to why.

Any help is much appreciated!

Asked By: user4154872

||

Answers:

list.sort() returns nothing (as shown here).

You have to call your_list.sort() first and then perform operations with your_list.

Answered By: ForceBru
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.