[英]Counting number of occurrences of objects with specific field value
我正在實施 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")
這個問題在這里已經有了答案。 但我想補充一點:
您正在查詢列表中的兩件事:
pixel.point
)。這將需要兩次迭代而不是一次 - 只需使用一個 for 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.