Python 计算具有特定字段值的对象的出现次数
我正在实现K-means算法,我需要计算分配给质心的点的数量。 在类点中,我有一个称为质心的字段。 我能否以某种方式使用Python的计数来计算指定给当前质心的点对象的数量 我的代码:Python 计算具有特定字段值的对象的出现次数,python,python-3.x,Python,Python 3.x,我正在实现K-means算法,我需要计算分配给质心的点的数量。 在类点中,我有一个称为质心的字段。 我能否以某种方式使用Python的计数来计算指定给当前质心的点对象的数量 我的代码: def updateCentroids(centroids, pixelList): k = len(centroids) centoidsCount = [0]*k #couts how many pixels classified for each cent. centroidsSu
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循环