-1

I have a program which contains a list, and in this list are either strings or objects of a class A. A sample list looks something like this:

['foo', 'bar', A('m',2), 'asdf', A('c', 2)]

As you can see, the class accepts a character and an integer value for its constructor.

I'm trying to write a conditional such that it finds the number of occurrences of the function with a specific first parameter. For instance, I want to find how many items in the list are of the form A('m', x) where x is any integer, which in this case would be 1.

How could I write an if statement to check for these elements? For now, I have:

if (listEle = A(desiredCharacter, any(1,2,3,4,5,6,7,8,9)))

Is this correct, and if yes, is there an easier way to do this?

David Buck
  • 3,752
  • 35
  • 31
  • 35

2 Answers2

0

Strange question, but

class A(object):
  def __init__(self, char, var):
  self.char = char

# Test an instance
a = A('m',8)
type(a) == A #True

# Number of occurrences of instances of A in a list
mylist = [0,1,a,2,A('f',3)]
len(list(filter(lambda el: type(el)==A, mylist))) #or the following
sum(list(map(lambda el: isinstance(el,A), mylist)))

aless80
  • 3,122
  • 3
  • 34
  • 53
0

You can do also:

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

    def __repr__(self):
        return f'My name: {self.name}\nMy num: {self.num}'


a1 = A('m', 2)
a2 = A('e', 7)
l = ['foo', 'bar', a1, 'asdf', a2]

for item in l:
    if isinstance(item, A) and isinstance(item.num, int):
        print(item)
David Meu
  • 1,527
  • 9
  • 14