import json points = [(0, 0), (1, 0), (3, 2), (4, 2)] labels = [0, 0, 1, 1] query = (3, 1) k = 3 # 平方距离与欧氏距离的排序相同。枚举索引保留标签与样本的对应关系。 distance = [(a - query[0]) ** 2 + (b - query[1]) ** 2 for a, b in points] neighbors = sorted(range(len(points)), key=lambda index: distance[index])[:k] votes = sum(labels[index] for index in neighbors) label = int(votes > k / 2) assert neighbors == [2, 3, 1] and label == 1 result = {"squared_distances": [distance[index] for index in neighbors], "votes": votes, "label": label} print("LAB_RESULT " + json.dumps(result, ensure_ascii=False))