Python Count Elements in a List of Objects with Matching Attributes

后端 未结 5 652
谎友^
谎友^ 2021-02-01 13:03

I am trying to find a simple and fast way of counting the number of Objects in a list that match a criteria. e.g.

class Person:
    def __init__(self, Name, Age,         


        
5条回答
  •  情深已故
    2021-02-01 13:19

    I know this is an old question but these days one stdlib way to do this would be

    from collections import Counter
    
    c = Counter(getattr(person, 'gender') for person in PeopleList)
    # c now is a map of attribute values to counts -- eg: c['F']
    

提交回复
热议问题