Search code examples
pythonloopscountsumboolean

Counting Objects in a List according to a Boolean property


I have a list of objects with a boolean property.

I'd like to count these objects according to this boolean property - None's included.

Are there functions in the standard library that would be more efficient, terser, or more Pythonic than fully writing out a loop to iterate over them?

Counter does not seem appropriate, and this nor this solve the problem - as far as I can tell.

class MyObject():
    def __init__(self, moniker, booleanVariable):
        self.name = moniker
        self.state = booleanVariable

def _myCounterMethod(list):
    # code goes here
    return counts

myList = []
myList.append(MyObject("objectOne", True))
myList.append(MyObject("objectTwo", False))
myList.append(MyObject("objectThree", None))

counts = _MyCounterMethod(myList)
print(counts)
>>>[('True', 1), ('False', 1), ('None', 1)]

My current solution:

def _myCounterMethod(list):
    trueCount = 0
    falseCount = 0
    noneCount = 0
    for obj in list:
        if obj.state == True:
            trueCount += 1
        elif obj.state == False:
            falseCount += 1
        elif obj.state == None:
            noneCount += 1
    countsList = [('True', trueCount), ('False', falseCount), ('None', noneCount)]
    return countsList

Solution

  • Use collections.Counter:

    import collections
    
    
    class MyObject():
        def __init__(self, moniker, booleanVariable):
            self.name = moniker
            self.state = booleanVariable
    
    
    my_list = [MyObject("objectOne", True), MyObject("objectTwo", False), MyObject("objectThree", None)]
    
    counts = collections.Counter(str(e.state) for e in my_list)
    print(counts)
    

    Output

    Counter({'True': 1, 'False': 1, 'None': 1})
    

    If strictly list output is needed do:

    result = list(counts.items())
    print(result)
    

    Output

    [('True', 1), ('False', 1), ('None', 1)]