python-3.x 我不断得到KeyError:0,似乎有什么问题?

d7v8vwbk  于 2022-12-20  发布在  Python
关注(0)|答案(1)|浏览(136)
def get_new_centroid(clustered_points, k_centroids):
    clusters = [] #dictionary to hold clusters with new centroids
    for i in range(k_centroids):
        new_centroid = compute_new_centroid(clustered_points[i])#compute for new centroids for n centroids
        temp = new_centroid, clustered_points[i] #return an array of tuples with new centroids and clustered points
        clusters.append(temp)
    return clusters

def compute_new_centroid(elem):
    new_centroid = []
    for i in range(2):
        total = 0
        for j in range(len(elem)):
            total = total + elem[j][i] #compute for new centroids
        total = total / len(elem) #compute for new centroids
        new_centroid.append(total)
    return new_centroid

这是代码片段,我一直在
第一个月
我试着去查是不是关于作业的但不是

lawou6xi

lawou6xi1#

当clustered_points中没有与i中的值匹配的键时,就会发生KeyError。也许您可以打印clustered_points中的所有项,以检查i可能具有的值的范围?

相关问题