-2

I'm implementing the K-means algorithm and I need to count how many points are assigned to a centroid.
In the class Point, I have a field called centroid.
Can I use Python's count in some way to count the number of Point objects that are assigned to the current centroid?

my code:

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
gusfring
  • 35
  • 6

1 Answers1

0

If I understand you correctly you want to do something along the following:

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")

This question would already be answered here. But I would like to add something:

You are querying the list for two things:

  1. How many objects match, and
  2. the sum of their values (pixel.point in your code).

That would require two iterations instead of one - just use a single for loop.

asynts
  • 2,213
  • 2
  • 21
  • 35