rosannavh
rosannavh

Reputation: 195

Counting the occurence of instances of a certain class in list of lists

I have list of lists in which I want to count the number of B() and C() instances and am looking for a suitable method to do this. Using collections.Counter() and the .count() function have resulted in strange results, and I suspect I do not fully understand how list of lists work in python, or how lists of class instances work in python.

This is the list of lists:

lst = [[B() for w in range(x)] for h in range(y)]

with

 class A():
    def __init__(self, name):
        self.name = name

 class B(A):
     def __init__(self, name = "B"):
         A.__init__(self, name)

     def update(self):
         if random.random() < 0.05: 
             return C()
         else: return self

 class C(A):
     def __init__(self, name = "C"):
         A.__init__(self, name)

And, I use the below code to randomly change B() instances in lst into C() instances:

for row in range(y):
    for column in range(x):
        lst[row][column] = lst[row][column].update()

How do I count the number of B() and C() instances in the list?

Upvotes: 1

Views: 103

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20414

You can use isinstance()

You can check what class an element is with isinstance().

Here is an example:

>>> a = C()
>>> isinstance(a, C)
True

So if you have your list, you can do:

occurrences_of_B = sum(isinstance(i, B) for r in list for i in r)
occurrences_of_C = sum(isinstance(i, C) for r in list for i in r)

you can get the occurrences of the B() and C() classes.

Essentially, we are using a generator comprehension to apply the isinstance() function to every element in the list. We then use sum on the generator as True evaluates to 1 and False to 0, so we will get the total count.

As a side note, although I said it is not good practice to name a list 'array', it is actually worse to name it exactly 'list' as this prevents you from being able to use the list() function! Better would probably be lst or l. :)

Upvotes: 1

Related Questions