计算具有特定字段值的对象的出现次数

2024-09-30 22:18:20 发布

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

我正在实现K-means算法,我需要计算分配给质心的点数。
在类Point中,我有一个名为centroid的字段。
我能以某种方式使用Python的count来计算分配给当前质心的Point对象的数量吗?你知道吗

我的代码:

def updateCentroids(centroids, pixelList):

    k = len(centroids)
    centoidsCount = [0]*k #couts how many pixels classified for each cent.
    centroidsSum = np.zeros([k, 3])#sum value of centroids
    for pixel in pixelList:
        index = 0
        #find whitch centroid equals
        for centroid in centroids:
            if np.array_equal(pixel.classification, centroid):
                centoidsCount[index] += 1
                centroidsSum[index] += pixel.point
                break
            index += 1
    index = 0
    for centroid in centroidsSum:
        centroids[index] = centroid/centoidsCount[index]
        index += 1

Tags: in算法forindexnpmeanspointpixel
1条回答
网友
1楼 · 发布于 2024-09-30 22:18:20

如果我对你的理解是正确的,你想做以下几点:

from dataclasses import dataclass

# the type doesn't matter, this is just an example
@dataclass
class A:
  value: int

lst = [A(1), A(2), A(3), A(4), A(5), A(6)]

# you can check for any condition here
no_evens = sum(item.value % 2 == 0 for item in lst)

print(f"there are {no_evens} even numbers in the list")

这个问题已经得到了回答。但我想补充一点:

您正在查询列表中的两件事:

  1. 有多少个对象匹配,以及
  2. 它们的值之和(pixel.point在代码中)。你知道吗

这将需要两次迭代而不是一次-只需使用一个for循环。你知道吗

相关问题 更多 >