我正在实现K-means算法,我需要计算分配给质心的点数。
在班级Point
,我有一个名为centroid
的字段。
我可以用某种方式使用Python的计数来计算分配给当前质心的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
如果我理解正确你想要做以下事情:
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")
here已经回答了这个问题。但我想补充一点:
您正在查询列表中的两件事:
pixel.point
)。这将需要两次迭代而不是一次 - 只需使用一个for循环。